Need help calling a JQuery function more than once without having to give every selector a function

StackOverflow https://stackoverflow.com/questions/16888478

  •  30-05-2022
  •  | 
  •  

Question

Okay so essentially I am creating a top ten list to be used multiple times on a site. However I want the contents of the list to be hidden and revealed one by one when clicking on the number. However, clicking on the first number causes the whole list to expand. Here is the JQuery:

    $(document).ready(function(){
       $("#articletext h2").click(function(){
          $(".revealTitle").fadeIn();
          $(".revealText").slideDown();
  });
});

Here is the HTML:

<h2>10. <span class="revealTitle">The Title To Fade In On Click</span></h2>

<span class="revealText">The Text to Slide Down On Click</span>

So what I want it to do is:

  • When the number (i.e 10.) is clicked, only that numbers revealTitle and revealText comes up.
  • Similarly when the next number is clicked (i.e 9.) 9.'s revealTitle and revealText come up.

Thanks In Advance.

Was it helpful?

Solution

Use context Selector

This will make sure only the elements with .revealText and .revealTitle are searched within the current context (Which here is the h2 element that was clicked)

 $(".revealTitle", this).fadeIn();
 $(this).nextAll(".revealText").first().slideDown();

OTHER TIPS

use $(this) selector and find method to target the correct children:

$(document).ready(function(){
    $("#articletext h2").click(function(){
          $(this).find(".revealTitle").fadeIn();
          $(this).find(".revealText").slideDown();
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top