Jquery Basic Beginner Question: How do I make my function reusable?

I've spent the last few hours trying to do this myself and using Google to find a solution, to no avail.

So, if you can help, I would super appreciate it!

Basically I have a page that has 3 separate biographies in a preview that only shows the first paragraph of each biography.

When you click "read more" for one biography, it opens "full mode".

What's going on at the moment, if I click on the read more link, it will open the full mode for all 3 biologists.

How can I edit the following code like this:

  • It only opens the fully functional biography of the link I click on
  • Make it reusable so I don't have to duplicate the code 3 times for each biography.

the code:

$("a#btnReadMore").click(function() {
    $('.readMoreSlider').slideToggle("fast");
    $(this).toggleClass("readMoreSliderActive"); 
    return false;
});

      

Thanks for your help!

+2


a source to share


2 answers


It depends on what your markup looks like. Identifiers must be unique. I'm going to assume:

<div class="bio">
  <p>...</p>
  <a class="readMore" href="#">read more</a>
  <div class="more">
    <p>...</p>
    <p>...</p>
    <p>...</p>
  </div>
</div>

      

with CSS:



div.more { display: none; }

      

and Javascript:

$(function() {
  $("a.readMore").click(function() {
    $(this).next("div.more").slideToggle();
    return false;
  });
});

      

+1


a source


$("a.btnReadMore").click(function(){ 
//--^ - Make 'btnReadMore' a CSS class, not an ID

  // with this you reference *all* elements of class 'readMoreSlider', 
  // but you want only a single one
  $('.readMoreSlider').slideToggle("fast"); 

  // this should be okay
  $(this).toggleClass("readMoreSliderActive"); 
  return false; 
});

      

So, if you have hypothetically:

<div class="bio">
  <div class="readMoreSlider">The bio Text...</div>
  <a class="btnReadMore">Read more</a>
</div>

      



You will need this modification to find the correct one readMoreSlider

for a specific click.

$(this).parent('.bio').find('.readMoreSlider').slideToggle("fast"); 

      

Depending on your actual markup, you might look slightly different.

0


a source







All Articles