I have hamburger and menu on the left side, which has width: 0px;
How can I do after click on hamburger menu changes width to 250px
, and second click change width to 0px
?
var hamburger = $('.hamburger-menu__list').css('width');
$('.hamburger-toggle').click(function(){
$(this).toggleClass('open');
if (hamburger == '0' ) {
$('.hamburger-menu__list').css('width', 250);
}
else {
$('.hamburger-menu__list').css('width', 0);
};
});
This will work. You have to check hamburger width everytime.
$('.hamburger-toggle').click(function(){
var hamburger = $('.hamburger-menu__list').css('width');
$(this).toggleClass('open');
if (hamburger == '0' ) {
$('.hamburger-menu__list').css('width', 250);
}
else {
$('.hamburger-menu__list').css('width', 0);
};
});
You can still cache element
but access width every time click
is invoked.
Another suggestion is to use ternary-operator
as this is ideal use case to use it.
var hamburger = $('.hamburger-menu__list'); $('.hamburger-toggle').click(function() { $(this).toggleClass('open'); var hamburgerWidth = hamburger.css('width'); $('.hamburger-menu__list').css('width', hamburgerWidth == '0' ? 250 : 0); });
You need to check the width every time you click on the button, also you need to parseInt the width to get a right number, css('width')
returns the value with prefix px
eg 250px
so parseInt will remove the prefix and returns pure number, Try this:
$('.hamburger-toggle').click(function(){
var hamburgerWidth = parseInt($('.hamburger-menu__list').css('width'));
$(this).toggleClass('open');
if (hamburgerWidth === 0) {
$('.hamburger-menu__list').css('width', 250);
} else {
$('.hamburger-menu__list').css('width', 0);
};
});
var $hamburger = $('.hamburger-menu__list').css('width'), $hamburgerToggle = $('.hamburger-toggle'), isOpen = false; function toggleMenu() { isOpen = !isOpen; $hamburgerToggle.toggleClass('open', isOpen); $hamburger.width(isOpen ? 250 : 0); } $hamburgerToggle.click(toggleMenu);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You are doing DOM manipulation. It is bad practice to relay on this, because it is asynchronous. A state variable ( isOpen
) helps to have only one source for the state (single source of truth).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.