skip to Main Content

I want to use this code for all the names and not do one sepret everytime

html code:

<div id="one" class="text-container"> 
  <span> Campfire Cooking in Another World with my Absurd Skill</span> 
  <div class="fader fader-left"></div>
  <div class="fader fader-right"></div>
</div> 

Javascript code:

let container1 = document.querySelector("#one");
let text1 = document.querySelector("#onespan");

if (container1.clientWidth < text1.clientWidth) { 
  text1.classList.add("animate"); 
}

I tried that code but it one does one name and not the rest.

2

Answers


  1. Does something like this help?

    let container = document.querySelectorAll(".text-container");
    let text = document.querySelectorAll("span");
    
    for (let i=0; i<container.length; i++) {
      if (container[i].clientWidth < text[i].clientWidth) {
        text[i].classList.add("animate");
      }
    }
    
    Login or Signup to reply.
  2. Fix

    Instead of doing a querySelector based one element using its ID. We can query multiple elements using querySelectorAll and do a query based a class, since an ID should one be used once.

        // this will get all the 16 elements, as long as they use this class.
        const containers = document.querySelectorAll(".text-container"); 
        
        
        for (let i=0; i<containers.length; i++) {
          // for each container we will need to find its text element we want to animate
          const text = containers[i].querySelector("span");
    
          if (containers[i].clientWidth < text.clientWidth) {
            text.classList.add("animate");
          }
        }
    

    instead of using a for loop you could also use a forEach which many people prefer as it easier to read. If you like the for loop more, stick with that!

        // this will get all the 16 elements, as long as they use this class.
        const containers = document.querySelectorAll(".text-container"); 
        
        containers.forEach((container) => {
            // for each container we will need to find its text element we want to animate
            const text = container.querySelector("span");
        
            if(container.clientWidth < text.clientWidth) {
              text.classList.add("animate");
            }
          })      
        }
    

    Advice

    I would recommend adding a specific class for those 16 elements that you won’t accidentilly reuse. This could be more likely with a generic name like .text-container instead of going with something like .js-animated-card.

    Adding js- as a prefix could help you easily separate the classes you use for styles and the classes you added to query the element in JS. This way you can also move/edit/rename you style classes without having the risk that you might break you javascript code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search