JDavies
JDavies

Reputation: 2770

jQuery function to only run on the element clicked

I'm trying to implement an accordian style box on some content. However there are 4-6 of these boxes on 1 template, all with different classes for obvious reasons. However I want to try and make the code as easy to read as possible and I don't want to duplicate the code for each class name. I'm assumung jQuerys (this) method would work but i'm not 100% sure how to use it.

Here is my JS code:

        <script type="text/javascript">
    $(document).ready(function(){
        $(".block-50_hoverHeader").click(function (){
           //alert("clicked");
            $(".scrollText").slideToggle(1000);

        });

        });


</script>

So the .scrollText class is the div that holds all the content which needs to be displayed after the onClick function. But currently when I click the header all the .scollText divs appear on the page. So i want it to only appear on the parent header div that is being clicked.

Here the HTML:

<div class="block-50 left textHoverWrapOne">
    <img src="" alt="" /> (Image working as BG Image)
    <div class="block-50_hoverHeader"><p>This is a header!</p></div>
    <div class="block-50_textHoverOne trans_click scrollText">
        This is the content that needs to be displayed after the 
    </div>
</div>

Upvotes: 0

Views: 1457

Answers (3)

Romaindr
Romaindr

Reputation: 311

Why not targeting the whole div??

jQuery(function ($) {
    $(".block-50").click(function () {
        $(this).find('.scrollText').slideToggle(1000);
    });
});

Upvotes: 0

James Montagne
James Montagne

Reputation: 78630

There are a number of ways to accomplish this. I prefer to grab the shared parent and then use find as I find this is a bit less likely to break due to minor modifications to the html structure.

$(".block-50_hoverHeader").click(function (){

    $(this).closest(".textHoverWrapOne").find(".scrollText").slideToggle(1000);

});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Find the scrollText relative to the clicked block-50_hoverHeader element. In this case it is the next sibling, so you can use .next()

Inside the event handler this points to the element in which the handler is registered, in this case it is the block-50_hoverHeader element, so we can find the next scrollText using $(this).next()

jQuery(function ($) {
    $(".block-50_hoverHeader").click(function () {
        $(this).next().slideToggle(1000);
    });
});

Demo: Fiddle

Upvotes: 3

Related Questions