I'm trying to make a side menu that opens and closes from the left when you press the menu button. Got the css, html code running properly but I can't figure out what I'm doing wrong with the script. It works perfectly but only once: When I press the menu button it comes out, press it again and it goes back just as intended. The problem is if I press it again it shows and it goes back by itself. Can anyone help me? Here is my script:
$(document).ready(function(){
$('.menu-icon').click(function(){
$('#navigator').animate({left:'0px'},200);
$(this).animate({left:'250px'},200);
$('.menu-icon').click(function(){
>$('#navigator').animate({left:'-250px'},200);
>$(this).animate({left:'0px'},200);
});
});
>});
You have placed a click handler inside a click handler so it will run multiple times. Twice first time, then three times, then four times etc.
You need to have a single handler and decide how to animate based on the current state of the element. e.g. something like the following (not tested):
$(document).ready(function () {
$('.menu-icon').click(function () {
if ($('#navigator').css("left") != "0px") {
$('#navigator').animate({
left: '0px'
}, 200);
$(this).animate({
left: '250px'
}, 200);
} else {
$('#navigator').animate({
left: '-250px'
}, 200); > $(this).animate({
left: '0px'
}, 200);
}
});
});
I would suggest testing the "current state" using a class you toggle on the element as testing css values is notoriously unreliable during animation.
e.g. something like:
if ($('#navigator').toggleClass("open").hasClass("open")) {
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加