skip to Main Content

Is there a way to do this in Javascript?
What I am trying to do is, when on click of a div then add a class "active" and remove it after a while. When adding active class to it’s parent div then I am going to play with some content within it’s div.

I am able to do it in jQuery but I am unable to do exactly in Javascript.

This is the code I wrote in jQuery.

HTML

<div class="main-wrapper">
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
  </div>

jQuery

jQuery('.content').on("click", function () {
  jQuery(this).addClass("active");
    setTimeout(RemoveClass, 5000);
    });
    function RemoveClass() {
     jQuery(this).removeClass("active");
  }

This is in Javascript I am trying but it’s working only for one item.

 function showMessage(){
     document.querySelector(".content").classList.toggle("active");
   setTimeout(() => {
     document.querySelector(".content").classList.toggle("active");
   }, 600)
 }

2

Answers


  1. This can be achieved in Javascript using target property of Event to get the clicked element and then toggling the active class for that specific element. Also as an improvement to your code, you can leverage the concept of Event delegation by attaching a single event listener to the parent instead of attaching them to every .content divs.

    function showMessage(e) {
      const clickedElement = e.target;
      if (clickedElement.classList.contains("content")) {
        clickedElement.classList.add("active");
        setTimeout(() => {
          clickedElement.classList.remove("active");
        }, 5000);
      }
    }
    
    document.querySelector('.main-wrapper').addEventListener('click', showMessage);
    .content:hover {
      color: red;
    }
    <div class="main-wrapper">
      <div class="content">
        Content div
      </div>
      <div class="content">
        Content div
      </div>
      <div class="content">
        Content div
      </div>
      <div class="content">
        Content div
      </div>
      <div class="content">
        Content div
      </div>
    </div>
    Login or Signup to reply.
  2. Vanilla JS :

    document.querySelector('.content').addEventListener('click', (event)=> {
      event.target.classList.add('active');
      setTimeout(() => RemoveClass(event), 5000);
    });
    
    function RemoveClass(ev) {
      ev.target.classList.remove('active');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search