Javascript/Jquery: IF Statement always runs
The code always runs when I click the sidebar button. It just keeps on adding 260px each time moving it more to the right. But it should stop after the first click.
$(document).ready(function() {
if ($('#sidebar').css('left') === '-260px') {
$('#btnsidebar').click(function() {
$('#sidebar').animate({left: '+=260',}, 1000);
});
$('#btnsidebar').click(function() {
$('#btnsidebar').anima开发者_StackOverflowte({left: '+=260',}, 1000);
});
}
});
$(document).ready(function() {
$('#btnsidebar').click(function() {
if ($('#sidebar').css('left') === '-260px') { // put if block inside the event
$('#sidebar').animate({left: '+=260',}, 1000);
$('#btnsidebar').animate({left: '+=260',}, 1000); // you are not required to add another click function for doing this
}
});
});
Move if
to the click handler body:
$('#btnsidebar').click(function() {
if ($('#sidebar').css('left') === '-260px')
$('#btnsidebar').animate({left: '+=260',}, 1000);
});
You add these event handlers conditionally, but the action (the animation) inside the event handlers is unconditional. Add an appropriate condition inside the event handlers (you can propably just copy it).
You need to have your if statement inside not outside.
$('#btnsidebar').live('click', function() {
if ($('#sidebar').css('left') === '-260px') {
$('#sidebar').animate({
left: '+=260',
}, 1000);
}
});
精彩评论