Reputation: 615
I am trying to make hover and click events for an element both animate the same (in this case top
) property.
look at this Fiddle: http://jsfiddle.net/XC9Xu/1/
There is an a
fixed at the top with top:-50px
and height=100px
,
1- when you hover it's top animates to top=0
and on mouseleave top becomes top=-50
again.
2- on click: animate top=200px
So the problem is, you click and dont move the cursor, everything is fine, but as soon as you move the cursor it says: hey, where is the element I was over it, I am not over it now, go back to top=-50px
:D
I need to tell it forget about the past and look to the future!
What I expect:
I expect that the element remain at top=300px
after click and don't come back to top=-50px
when you move the mouse after click. Then if you move your cursor again over it its top goes from 300 to 0 and so on...
$(document).ready(function(){
$('a')
.hover(
function(){
$(this).animate({top:0});
},
function(){
$(this).animate({top:-50});
}
)
.on("click",function(){
$(this).animate({top:300});
});
});
a{
display:block;
position:fixed;
top:-50px;
left:0;
width:100%;
height:100px;
background:#ccc;
}
Upvotes: 0
Views: 72
Reputation: 10077
Just set a flag, and use it to enable/disable the hover functionality.
var click_triggered = false;
$(document).ready(function(){
$('a')
.hover(
function(){
if(!click_triggered){
$(this).animate({top:0});
}
},
function(){
if(!click_triggered){
$(this).animate({top:-50});
}
}
)
.on("click",function(){
click_triggered = true;
$(this).animate({top:300});
});
});
or if you wanted it to revert after a second click you would do something like this click handler:
.on("click",function(){
click_triggered = !click_triggered;
$(this).animate({top:300});
});
Upvotes: 1
Reputation: 2419
This does the trick
$(document).ready(function(){
reduceHeight = function(){
$(this).animate({top:-50});
};
$('a')
.hover( function(){
$(this).animate({top:0});
$(this).bind('mouseleave', reduceHeight);
})
.click( function(){
$(this).unbind('mouseleave');
$(this).animate({top:300});
});
});
Upvotes: 0