Jquery show / hide small issue - made a video to explain my pain

I got a little show / hide thing going on a test page but I have noticed something that is a bit of a pain.

http://jsfiddle.net/trk5d1fx/11/

When you click the read more, the read less button shows and that is fine. But if you click show more on more than two, it doesn’t show the read less on the second one - ugh.

Please someone help me with this and suggest what I could do to improve me jQuery :slight_smile:

My explanations are not the best so here is a little video:

Cheers!

The error is coming from $(".more-content") referring to more than one part of your html. You need to refer to something unique.

You should replace this line:

var txt = $(".more-content").is(’:visible’) ? ‘Read More >>’ : ‘Read Less <<’;

With this one:

var txt = $(this).text() === ‘Read Less <<’ ? ‘Read More >>’ : ‘Read Less <<’;

1 Like

Sorry, there are some auto-formatting issues with the quotations here. Replace the quotation marks in my solution with new single or double quotation marks.

1 Like

Thank you for this and the explanation, this rocks. Now if only I could sort the jumping issues. Cheers :slight_smile:

Ok sorted the jumping issues with this:

$(document).ready(function(){
$(".more-content").hide();

$(".read-more").on("click", function (e) {
    var txt = $(this).text() === "Read Less <<" ? "Read More >>" : "Read Less <<";
    $(this).text(txt);
    $(this).next('.more-content').slideToggle(200);

    //Prevent Issues from happeing.
    e.preventDefault();
});

});

//The e in the the function ()
$(".read-more").on("click", function (e) {

 //This at the bottom
 e.preventDefault(); 

This now have solved the jumping issues yay!

Thanks for all help :slight_smile:

Could anyone expand on why this solves it? I can not find an answer!

Using preventDefault() on an event stops its default behavior. In jQuery, the default behavior of a click event is to navigate somewhere via the ‘href’ property. If no href property is provided, it will navigate to the top of the page as its default action. You can stop this behavior by calling preventDefault() on the event object (which you have done).

For more info see:

https://api.jquery.com/event.preventDefault/

1 Like

Thanks very much for that - I’ve bookmarked :slight_smile: