Jquery toggle using 2 elements

723 views Asked by At

this is my script, I'm using a toggle so I can animate a sliding menu.

    $("div.show-menu").click().toggle(
        function() {
            // first alternation
            $("#slideover").animate({
                right: "512px"
                }, 300);
            $(".menu-button").html('close menu');


        }, function() {
            // second alternation
            $("#slideover").animate({
                right: "0"
                }, 300);
            $(".menu-button").html('open menu');

    });

Though I really need the toggle to work using 2 elements on the page. For example see below...

<div class="show-menu one">open menu</div> // this is element one

<div class="show-menu two">open menu</div> // this is element two

I need it so, if element one get's click first, you can close the menu using element two on the first click. What is happening now is that you have to click element two twice in order for it to close the menu - vice versa

I guess this is the toggle coming into play, any help would be great thanks.

Cheers Josh

2

There are 2 answers

3
Jasper On BEST ANSWER
$('.show-menu').on('click', function () {

    //check the state of the .menu-button, if it's closed then run the open animation, if it's open then run the close animation
    if ($(".menu-button").html() == 'close menu') {
        $("#slideover").animate({
            right: "0"
        }, 300);
        $(".menu-button").html('open menu');
    } else {
        $("#slideover").animate({
            right: "512px"
        }, 300);
        $(".menu-button").html('close menu');
    }
});

.on() is new in jQuery 1.7 and replaces .bind() in this instance, if you are using jQuery < 1.7 then use .bind().

2
Richard Banks On

What about

$('.show-menu').on('click', function () {
    if ($("#slideover").css("right") == '512px') {
        $("#slideover").animate({
            right: "0"
        }, 300);
        $(".menu-button").html('open menu');

    } else {
        $("#slideover").animate({
            right: "512px"
        }, 300);
        $(".menu-button").html('close menu');
    }
});