순댓국 2024. 1. 2. 19:43
728x90
반응형
SMALL

 

 

 

HTML

<i class="fab fa-twitter fa-3x"></i>
<i class="fab fa-youtube fa-3x"></i>
<i class="fab fa-facebook fa-3x"></i>

폰트어썸을 이용해 트위터, 유튜브, 에? 페이스북이 음 넣어주기

 

<div class="counter" data-target="12000"></div>
<div class="counter" data-target="5000"></div>
<div class="counter" data-target="7500"></div>

 

Notice the link element has two custom data attributes: data-toggle and data-target . The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an ID of “basicModal” will appear

 

 

CSS

css 는 심플하다. 

 

 

JS

const counters = document.querySelectorAll(".counter");

 

counter 라는 클래스명을 가진 div가 3개 이므로 selectorAll 한 다음 .counter을 가져온다. 

 

counters.forEach((counter) => {
counter.innerText = "0";

forEach로 iteration 해주고 

가장 먼저 0의 값으로 innerText에 설정

 

const updateCounter = () => {
const target = +counter.getAttribute("data-target");
const c = +counter.innerText;

const increment = target / 1000; //duration big number takes long

console.log(increment);

 

data-target을 가져와서 update를 한다.

js 안에서 처리 가능 한 부분을 html getAttribute 한 이유는?

 

Dynamic Configuration: The data-target attribute can be set in the HTML markup, allowing for dynamic configuration of each counter. This way, you can change the target value for a counter without modifying the JavaScript code directly.

 

타겟밸류를 바꿀 때 js와 상관없이 쉽게 바꾸는 그런 의도 일까!? 

  1. Integration with Server-Side Code: If the HTML is generated dynamically on the server side, using data-target allows you to pass the target values from the server to the client easily. The server can set these attributes based on some logic or data.

음 이게 더 적절한 이유 같은데,,

이번에 좋아요 누른 횟수를 서버에 저장하여 window 로딩시에 새로운 값이나 초기화가 되는 것이 아니라 서버에서 저장된 값을 그대로 유지하며 수정 변경시 서버에서 저장되게 하였었다.

서버에서 클라이언트로 보낼 때 쉽다. 음.... 

 

Overall, using getAttribute('data-target') provides a flexible and organized way to associate configuration data with HTML elements, especially when you want to set or modify values externally without changing the JavaScript code. It aligns with the principle of separating content (HTML), presentation (CSS), and behavior (JavaScript).

 

 

console.log(increment);
if (c < target) {
counter.innerHTML = `${Math.ceil(c + increment)}`;
setTimeout(updateCounter, 1);
} else {
counter.innerText = target;
}
};

 

c는 innerText의 값이다. 그 값에 target보다 낮으면 증가

setTimeout(function(){ //code goes here }, 2000); //Time before execution

updateCounter 함수를 실행시켜주고 1은 시간

 

그러고보니 몇 일 전에 좋아요는 어떻게 한거더라..... data-target 안 쓴거 같은데 ... 큰 일이다... 뭐 다음에는 이 방식으로 해보는 걸로..

728x90
반응형
LIST