Search code examples
jqueryshow-hide

jQuery on click of button show and hide closest divs


Hi I am using masonry with laravel and I am basically loading my blogs into a masonry layout. I have an abstract which i output as well as all the content, the content is hidden by default by css. I have a read more button once clicked adds a class to that div which expands the masonry block.

I also want to hide the abstract within this masonry block but I can't seem to be able to do this successfully, instead I am hiding all the abstracts on the page. I've tried using selectors such as parent and children but I don't think I am quite getting the concept here. Any have any ideas as to how I can hide the class div.abstract and show div.fullstroy when I click div.button #read-more ??

A simple version of my code is below or please view my JSFIDDLE

Any help much appreciated.

HTML:

<div id="masonary-blogs">
    <div class="one-third column">
        <h3>title</h3>
        <div class="abstract">
            <p>abstract</p>
        </div>
        <div class="fullstory">
            <p>fullstory</p>
        </div>
        <div class="button">
            <a href="#" id="read-more">Read more</a>
        </div>
    </div>
       <div class="one-third column">
        <h3>title</h3>
        <div class="abstract">
            <p>abstract</p>
        </div>
        <div class="fullstory">
            <p>fullstory</p>
        </div>
        <div class="button">
            <a href="#" id="read-more">Read more</a>
        </div>
    </div>
        <div class="one-third column">
        <h3>title</h3>
        <div class="abstract">
            <p>abstract</p>
        </div>
        <div class="fullstory">
            <p>fullstory</p>
        </div>
        <div class="button">
            <a href="#" id="read-more">Read more</a>
        </div>
    </div>

</div>

CSS:

.one-third {
    width:23%;
    background:#dedede;
    min-height:100px;

}
.column {
    display:inline-block;
    margin-left:5px;
    margin-right:5px;
}
.fullstory {
    display:none;
}
.gigante {
    width:100%;
}
.hide {
    display:none;
}

.show {
    display:block;
}

jQuery:

$('#masonary-blogs').on('click', 'a', function(e){
    var blogItem = $(this).parents('.one-third'),
        container = $('#masonary-blogs');

    e.preventDefault();
    console.log('Blog link click');

    $('.gigante').removeClass('gigante');
    $(e.target).parents('.one-third').addClass('gigante');
    $('.one-third').children('.abstract').hide();

});

Solution

  • well the .abstract div is a sibling not a parent or child to the button so it would be

    $('.button').on('click',function(){
      $(this).siblings('div.abstract').hide();
    })
    

    edit: or if you want to show the full story and hide the abstract it could be something like

    $('.button').on('click',function(){
      $(this).siblings('div').toggle();
    })