0
votes

I have created a simple "Show and Hide" toggle using Jquery but I want it to be specific to each div as I will be reusing the Class.

I know I have to use the (this) function but cant seem to place it correctly.

Please see fiddle

many thanks for you kind help.

    $(document).ready(function() {
    $('.showmenu').click(function() {
            $('.menu').toggle("toogle");
    });
});
4

4 Answers

1
votes

I'd suggest:

$(document).ready(function () {
    // attaching the click-event handler to the class:
    $('.showmenu').click(function () {
        // this is the DOM node of the clicked-element,
        // $(this) is the jQuery object formed from the clicked DOM node
        $(this)
          // traverses to the next sibling of the clicked element,
          // if it's a 'div' with the 'menu' class-name:
          .next('div.menu')
          // toggles that element:
          .toggle("toogle");
    });
});

$(document).ready(function () {
    $('.showmenu').click(function () {
        $(this).next('div.menu').toggle("toogle");
    });
});
<div class="showmenu">Click Here</div>
<div class="menu" style="display: none;">
    <ul>
        <li>Button1</li>
        <li>Button2</li>
        <li>Button3</li>
    </ul>
</div>
<div class="showmenu">Click Here</div>
<div class="menu" style="display: none;">
    <ul>
        <li>Button1</li>
        <li>Button2</li>
        <li>Button3</li>
    </ul>
</div>

References:

Recommended Reading:

1
votes

Use next(). Example:

$(document).ready(function() {
    $('.showmenu').click(function() {
        $(this).next('.menu').toggle("toogle");
    });
});
1
votes

You can try...

 $(document).ready(function() {
     $('.showmenu').click(function() {
         $(this).next().toggle("toggle");
    });
 });
0
votes
$(document).ready(function () {
    $('.showmenu').click(function() {
        $(this).children().toggle();
    });
});

I'm assuming what you want is for each div to toggle the visibility of its contents when clicked. The children selector would get every list nested under the div, even if there are multiple ones.

I edited your fiddle here. Check it out, you also had an error in your html (an extra </div>).