Fredtrix
Fredtrix

Reputation: 117

Get the .show to only show one div at the time

Basically I'm using the jQuery .show to view the sections that are hidden in my articles. And this works, but it's global. Which means that every section following a "read more" div is revealed when I press one of them.

How can I limit it so that after I press any of the "read more" div's only the following element (which in this case is hidden sections containing text) is made visible.

This is my current script for this feature:

$('div.showrest').click(function(){

    $(".blog > .invis").show("fast");

});

$('div.showless').click(function(){

    $(".blog > .invis").hide(500);

});

This is my current html structure:

<article class="blog">

    <h3> Title </h3>

    <p class="blog"> 

    Short summary here.

    </p>

    <div class="showrest"> Read more </div>

<section class="invis" style="display:none;">

    <p class="blog">  

    Here is the rest of the article.

    </p>

    <div class="showless"> Hide text </div>

</section>

    <footer class="blog">

    Footer text.

    </footer>

</article>

If only I had one article I wanted this feature on it wouldn't be a problem, but I got many and I would like this to be possible on all of them, but individually.

I know it is possible to do it with multiple different id's, classes and scripts. But I would prefer if it was all within the same .click script you see above.

I've been working to find a solution to the issue all day, but I just can't seem to figure it out.

Upvotes: 1

Views: 1314

Answers (4)

prakashapkota
prakashapkota

Reputation: 321

Use this & parents

$('div.showrest').click(function(){
    $(this).parents('article').find('.invis').show('fast');
});

$('div.showless').click(function(){
    $(this).parents('article').find('.invis').hide('fast');
});

Upvotes: 0

Bas Wildeboer
Bas Wildeboer

Reputation: 580

Change your jquery code like this:

$('div.showrest').click(function(){
    $(this).next().show("fast");
});

$('div.showless').click(function(){
    $(this).parent().hide(500);
});

This way you only trigger the show and hide on the relevant elements.

Upvotes: 0

sudhansu63
sudhansu63

Reputation: 6180

You can use the .closest selecter to do this.

$('div.showrest').click(function(){

    $(this).closest(".blog > .invis").show("fast");

});

$('div.showless').click(function(){

        $(this).closest(".blog > .invis").hide(500);

});

Upvotes: 0

Anton
Anton

Reputation: 32581

Something like this? multiple sections and multiple show/hides?

$('div.showrest').click(function () {
    $(this).next().show("fast");
});
$('div.showless').click(function () {
    $(this).closest('section').hide(500);
});

DEMO

Upvotes: 1

Related Questions