Reputation: 7
i have one header and one menu, the menu is an hidden div that appears when you click at a specific button.
When you click at this button, the hidden menu appears, when you click again, the menu disappears, as you can see, i'm using Toggle to do that.
But i'm having some problems, my header initial width is 100%, but when you open the menu it changes the value to 82, to give some space to menu.
When i click at the button the header div changes the value to 82%, but when i click again, the value keeps 82%, and i want to change to 100% again.
I created a jsfiddle to show whats happening:
When you click at hideshow the width changes, but when you click at hide/show again, the width doesn't change to 100% again.
Here my code
$("#hide").click(function(){
$("#menu").fadeToggle();
$('#header').toggle(function () {
$("#header").css({"width":"82%","left":"18%"});
}, function () {
$("#header").css({"width":"100%"});
});
});
Thank you.
Upvotes: 0
Views: 75
Reputation: 2557
You need to move the toggle
handler outside the click
handler, since the toggle
calls a click event.
From http://api.jquery.com/toggle-event/
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.
So this should work:
$("#hide").click(function(){
$("#menu").fadeToggle();
});
$('#header').toggle(function () {
$(this).css({"width":"82%","left":"18%"});
}, function () {
$(this).css({"width":"100%", "left":"0%"});
});
JSFiddle:
Upvotes: 1
Reputation: 3120
This isn't an exact solution to the css
not resetting, but this will get you your results.
Instead of using .toggle()
with .css()
, you should consider making a class with the desired css, and then using .toggleClass()
.
Example
JS
$("#hide").click(function(){
$("#menu").fadeToggle();
$('#header').toggleClass('shifted');
});
CSS
#header.shifted {
width: 82%;
left: 18%;
}
Upvotes: 2