Razvan Zamfir
Razvan Zamfir

Reputation: 4614

Show/hide menu with jQuery

I have a page with content (on the left) and sidebar (on the right). For screen widths <= 480px the 2 div's are placed one under the other (100% widths). The "Show/Hide" button that becomes visible is meant to toggle the sidebar's visibility when clicked. I use

$(".sidebar .box").slideToggle(200);

for this purpose.

See everything together on jsfiddle.

The problem: if I switch to wide screen and then back to narrow screen (width <= 480px) again, clicking the button produces a "back and forth" bug.

Where is my mistake?

Thank you!

Upvotes: 1

Views: 1508

Answers (3)

AGE
AGE

Reputation: 3792

I believe that your problem is that your slide function gets called continuously when your window is resized. Rather than have this event occur unchecked, try to control it using an event handler like so:

Use .one():

$('#your_element_id').one("click", function () {     
    $('.your_css_style_class').slideToggle(200); 
});

Another thing to keep in mind is that if down the line, you desire to display it hidden, you may want to use .slideDown() rather than .slideToggle() to begin with.

Here is a jQuery reference to the 'one' function: http://api.jquery.com/one

Upvotes: 1

indubitablee
indubitablee

Reputation: 8206

something like this? http://jsfiddle.net/jqdvj42u/3/

$(document).ready(function() {
     $("a.expander").click(function () {
        $(this).toggleClass('close');
        $(".sidebar .box").slideToggle(200);
    });
});

function showSidebar() {   
    if ($(window).width() <= 480) {
        // Close sidebar when window width <= 480px
        $(".sidebar .box").removeClass('open');
        // Click expander button to show/hide sidebar

    } else {
        $("a.expander").removeClass('close');
        // Open sidebar when window width > 480px;
        $(".sidebar .box").addClass('open');
    }
}
showSidebar();

$(window).resize(showSidebar);

your click shouldnt be called within showSidebar() because it'll bind the click event every time that function is called. resize triggers showSidebar() multiple times, so the click is bound multiple times. also, you should use jQuery 1.11 as the lowest version since its the most up-to-date version thats stable on IE<9. if you dont mind support on IE<9, use jQuery version 2.0 or higher.

Upvotes: 0

rubikonx9
rubikonx9

Reputation: 1413

I believe the reason is that this code:

$("a.expander").click(function () {
    $(this).toggleClass('close');
    $(".sidebar .box").slideToggle(200);
});

gets executed every time the function showSidebar is run, which is every time the window is resized. JQuery's click function adds a new event handler each time, and executes all of them on each window resize.

The solution would be to move the click handler registration outside of the function.

Upvotes: 1

Related Questions