Home > Software design >  How do I fade out any specific element that is clicked on using jQuery?
How do I fade out any specific element that is clicked on using jQuery?

Time:03-19

I'm trying to create a jQuery function to fade out any specific element that the user clicks on within the webpage.

I have tried using the universal selector to target all the elements, but then when I click an element every single element on the page fades away. Im trying to fade away only the clicked element and the rest of the page stays.

I was thinking of adding and event listener to all elements of the page and then removing the parent node of the clicked element?

Here is my code so far:

$("*").click(function () {
  $("*").fadeOut(3000);
});

So yeah that's the function I've created already.

Any ideas ?

Thanks

CodePudding user response:

You can use $(this) to refer to the item that was clicked, so it could become:

 $(this).parent().fadeOut(3000)

CodePudding user response:

You will have to target the element clicked. Because the click event propagates which results in the event handler for each element being executed. Event Propagation

So to achieve what you want you will have to stop the event from propagating. Below is a working sample of this.

$("*").click(function($event) {
  $event.stopPropagation();
  $(this).fadeOut(3000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div> first div</div>
<div> second div</div>
<div> third div</div>
<div> fourth div</div>

CodePudding user response:

You can change a few things to make your code work

  • Use .on() to bind click function to all elements (Difference between .on('click') vs .click()) Not mandatory but a good practice
  • use $(this) to target clicked element
  • Use e.stopPropagation(); to prevent event bubbling

Working code below

(Click on any item) [if you click on page area, the whole page would fade, so try to click on elements to see the effect)

$("*").on('click', function(e) {
  e.stopPropagation();
  $(this).fadeOut(1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>I am a Div</div>
<ul>
  <li> list 1 </li>
  <li> list 1 </li>
</ul>

  • Related