Reputation: 1204
Trying to do a simple animation on click. I have a panel thats hidden off to the right side (absolute positioned) when the user clicks the tab i want the panel to slide out. I can get the initial slide out to work but cant get the toggle to function properly
$('#sideTab').click(function() {
$('#sideCol').animate({'right':'0%'})
}, function ()
$('#sideCol').animate({'right':'-50%'})
});
$('#sideTab').toggle(function() {
$('#sideCol').animate({'right':'0%'})
}, function ()
$('#sideCol').animate({'right':'-50%'})
});
neither of these are working
fiddle: http://jsfiddle.net/BQE32/1/
when the green square is clicked the blue square should move left, and when its clicked again it should move back to original positioning
Upvotes: 1
Views: 1327
Reputation: 144659
click
doesn't accept two callback functions, you can read the right
property and set the proper value:
$('#sideTab').click(function () {
var $e = $('#sideCol');
$e.animate({
'right': $e.css('right') === '0px' ? '-50%' : '0px'
});
});
You can also use CSS transition
property and jQuery .toggleClass()
method:
CSS:
#sideCol {
-webkit-transition: right 400ms;
-moz-transition: right 400ms;
-o-transition: right 400ms;
transition: right 400ms;
}
#sideCol.right50 {
right: 50%;
}
JavaScript:
$('#sideTab').click(function () {
$('#sideCol').toggleClass('right50');
});
Upvotes: 2
Reputation: 5302
$('#sideTab').on('click', function() {
if ($(this).hasClass('toggled') === true) {
$(this).animate({'right': '-50%'}).removeClass('toggled');
} else {
$(this).animate({'right': '0'}).addClass('toggled');
}
});
This will check if the sidebar is already 'toggled', and if it is will remove the class and animate it back out of the frame (and vice versa).
Upvotes: 2