Home > database >  Changing class without variables in javascript
Changing class without variables in javascript

Time:09-29

I have attached 2 of my divs below. When the icon inside heart is clicked, if the class name is far then it should change from far to fas. But if the class name has been changed to fas, it should change back to far. I'm not sure how to do this becuase I have many divs.

<div class="cont">
     <h2>A header</h2>
     <div class="heart">
          <i onclick="like(example)"  class="fas fa-heart"></i>
     </div>
</div>
<div class="cont">
     <h2>A header#2</h2>
     <div class="heart">
          <i onclick="like1()"  class="fas fa-heart"></i>
     </div>
</div>

This is the javascript I currently have.

function like(example){
     if(example.classList=="far fa-heart"){
         example.classList.toggle="fas fa-heart";
     } else{
         example.classList.toggle="far fa-heart";
    }
}

I want this to be in just 1 function without making a variable for all the tags in javascript. I'm still learning... Thanks for your help!

CodePudding user response:

I can't find a good dupetarget for this. Basically, you can hook click on a parent element containing all of these (body if nothing else) and only take action if the click passed through the fa-heart element when bubbling:

theContainer.addEventListener("click", function(event) {
    // Did the click pass through an `.fa-heart` element?
    const heart = event.target.closest(".fa-heart");
    if (heart && this.contains(heart)) {
        // Yes, and that element is inside this container; toggle it
        heart.classList.toggle("far");
        heart.classList.toggle("fas");
    }
});

See closest, contains, and toggle for details.

Live Example:

CodePudding user response:

You can use a function that accepts an HTML element as a parameter and toggles the classes.

function like1(element) {  
  element.classList.toggle("fas");
  element.classList.toggle("far");
}
.fas {
  color: green;
}
.far {
color: red;
}
<div class="cont">
     <h2>A header</h2>
     <div class="heart">
          <i onclick="like1(this)"  class="fas fa-heart">Like</i>
     </div>
</div>
<div class="cont">
     <h2>A header#2</h2>
     <div class="heart">
          <i onclick="like1(this)"  class="fas fa-heart">Like</i>
     </div>
</div>

CodePudding user response:

Just toggle them both.

function toggleHearts()
 document.querySelectorAll(".heart")
   .forEach(elm => elm.addEventListener("click", (e) => {
      e.target.classList.toggle("far");
      e.target.classList.toggle("fas");
 }));
}
  • Related