Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having many JQuery Toggle buttons on the same page

Tags:

jquery

toggle

I just realized another problem with my so called "solution" =)

My JS Code:

<script type="text/javascript">
    $(function() {
        function runEffect(){ 
            var selectedEffect = $('#slide').val();
            var options = {};
            if(selectedEffect == 'scale'){  options = {percent: 0}; }
            else if(selectedEffect == 'size'){ options = { to: {width: 200,height: 60} }; }
            $("#effect1, #effect2").toggle(selectedEffect,options,500);
        };
        $("#moduleMenuBtn1, #moduleMenuBtn2").click(function() {
            runEffect();
            return false;
        });
    });
</script>

I have 9 boxes, all with a "Menu" button that should slide down a menu for a particular box (not all at once).

How can I change the code to get "Menu" button1 to react with "menu1" and not all menus at once?

My solution to have #menuBtn1, #menuBtn2, etc, is not working =)

like image 280
Erik Lydecker Avatar asked Dec 11 '25 00:12

Erik Lydecker


1 Answers

Instead of IDs (like your previous question) use classes, like this:

<div class="moduleMenuBtn">Menu</div>
<div class="effect">Some Content</div>

Then in your code you can use .next() to find the corresponding .effect relatively, like this:

$(function() {
    $(".moduleMenuBtn").click(function() {
        var selectedEffect = $('#slide').val();
        var options = {};
        if(selectedEffect == 'scale'){  options = {percent: 0}; }
        else if(selectedEffect == 'size'){ options = { to: {width: 200,height: 60} }; }
        $(this).parent().next(".effect").toggle(selectedEffect,options,500);
        return false;
    });
});

This makes it work for any number of .moduleMenuBtn and .effect pairs in the page. To see other methods to find things relatively, check out the tree traversal section of the API.

like image 110
Nick Craver Avatar answered Dec 15 '25 12:12

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!