Disable Anchor onclick [duplicate]
Possible Duplicate:
How to enable or disable an anchor using jQuery?
I've got an onclick
on an anchor which causes 2 divs to change their width (typical concept of sidebar toggling whilst enlarging the content). However, if I click this anchor and click it again whilst the animation is still playing, it will start the animation over from where the divs currently are (e.g. sideDiv is usually at 200px width, content at 1000px width, if i start the animation the sideDiv should go to 0 and the content to 1200, however, if I click again whilst side is at 100 and content at 1100, they'll toggle back to 300 and 900, which is not what I want).
So, logically I'll need to disable the anchor-onclick for the time the animation is played and enable it again, I know this procedure for buttons, is there anything similar for anchors?
Here's my code:
function toggleSideBar(e) {
barWidth = $('#resizableBar').wid开发者_开发问答th();
if ($('#content').width() >= "900") {
$('#content').animate({ width: ($('#content').width() - barWidth) }, 200, function () {
$('#resizableBar').animate({ width: "show" }, { duration: 200, queue: true});
});
}
else {
$('#resizableBar').animate({ width: "hide" }, 200, function () {
$('#content').animate({ width: ($('#content').width() + barWidth) }, { duration: 200, queue: true });
});
}
}
Here's the anchor:
<a id="btnSideDivSlide" onclick="toggleSideBar(this)" href="#">Sideslide</a>
Thanks,
Dennis
Something like this might work:
var _isAnimating;
function toggleSideBar(e) {
if (_isAnimating) return;
barWidth = $('#resizableBar').width();
if ($('#content').width() >= "900") {
_isAnimating = true;
$('#content').animate({ width: ($('#content').width() - barWidth) }, 200, function () {
$('#resizableBar').animate({ width: "show" }, { duration: 200, queue: true, complete: function(){ _isAnimating = false; }});
});
}
else {
_isAnimating = true;
$('#resizableBar').animate({ width: "hide" }, 200, function () {
$('#content').animate({ width: ($('#content').width() + barWidth) }, { duration: 200, queue: true, complete: function(){ _isAnimating = false; } });
});
}
}
(Not sure if my syntax is perfect, but you get the idea)
You could check at the beginning of your function whether the animation is running, and if so don't start it. A global boolean would do the trick.
In jQuery, the following will disable the onclick:
$("#btnSideDivSlide").unbind("click");
Then once its finished you can rebind:
$("#btnSideDivSlide").click(function(){
toggleSideBar(this);
});
If you put this following in your code, you could eliminate the onlcick event attribute from your HTMl altogether:
$(document).ready(function(){
$("#btnSideDivSlide").click(function(){
toggleSideBar(this);
});
});
This is called 'late binding' and helps to eliminate obstrusive JavaScript such as onlick=
from your HTML.
try
HTML
<a id="btnSideDivSlide" href="#">Sideslide</a>
jQuery
$('#btnSideDivSlide').bind ('click' , function () {
toggleSideBar(this);
})
精彩评论