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
This can be achieved in Javascript using
target
property ofEvent
to get the clicked element and then toggling theactive
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.Vanilla JS :