Multiple toggle buttons, 1 jQuery code

1.1k views Asked by At

Trying to work out if it's possible to have multiple toggle buttons on my page while not having to repeat jQuery .toggleClass code for each button (with different id's)? Maybe use 'this' or some other method?

$(document).ready(function(){
    $("button").click(function(){
        $("p").toggle('fast');
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>

<button>Toggle</button>

<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
  
<button>Toggle</button>

<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>

</body>
</html>

Thanks in advance!

3

There are 3 answers

0
Mohamed-Yousef On

to toggle the next p you need to use .next()

$(document).ready(function(){
    $("button").click(function(){
        $(this).next('p').fadeToggle('fast');
    });
});

to toggle the next p and next next p you need to use .next()

$(document).ready(function(){
        $("button").click(function(){
            $(this).next('p').fadeToggle('fast');
            $(this).next().next().fadeToggle('fast');
        });
    });

you can select your button ids like

 $("#button1, #button2").click();

I don't prefer your html structure .. if you can put each button and its P in one div it will be better to handle

0
Lee Li On

You can use event delegation.

For example, if you bind click event to buttons. I think you can use id or data attribute to differentiate which button is triggered. Then you can move forward.

0
pavankumar kavvuri On

$(function() { $('#toggle-event1,#toggle-event2,#toggle-event3,#toggle-event4,#toggle-event5').change(function() { let state1 = $(this).prop('checked'); //alert( "First handler for .toggle() called." );

                  alert(this.id);})