JQuery problem using .delegate() function, trouble binding function to elements...
I'm new to jquery and having a problem using .delegate() to bind a function to elements in my page.
I can't do this using .bind() because the DOM in the page changes when I partially reload part of the page.
I've looked at using .live() but it seems that this has been deprecated by .delegate().
I wondered if anyone might be able to help me as to where I might be going wrong?
I'm trying to build a tooltip that I can use throughout my site. I'm aware there are already libraries out jquery tools etc that have this functionality, but Id rather build a simple version myself.
Here's the code.
$jQuery.fn.myToolTip = function () {
var offTopSide = 0;
var offLeftSide = -360;
$(this).mouseover(function () {
//left side of button
var currentLeftPosition = $(this).position().left;
//top side of button
var currentTopPosition = $(this).position().top;
var myToolTip = $(this).next();
myToolTip.css("top", (currentTopPosition + offTopSide) + "px");
myToolTip.css("left", (currentLeftPosition + offLeftSide) + "px");
myToolTip.show();
});
$(this).mouseout(function () {
$(this).next().hide();
开发者_JS百科 });
}
$(document).ready(function () {
$(document).delegate('a', "mouseover mouseout", function () {
$(this).myToolTip();
});
});
Heres the html...
<a class="button" href="">Mouse over this link...</a>
<div class="tooltip" style="display: none;">
<div class="tooltip-inner">
tooltip1
</div>
<div class="clear">
</div>
</div>
At the moment this seems to work ONLY after you mouseover and mouseout of the link ONCE. Mousing over on the second time triggers the tooltip..
Apologies if this is something really obvious.
Regards
S
The way I'm reading it, you are calling myToolTip();
on the element on mouseover
and mouseout
in order to set the new mouseover
& mouseout
event callbacks so the second time you mouseover, the new event callbacks will get called.
you want to do this:
$(document).delegate('a', "mouseover", function (){
//left side of button
var currentLeftPosition = $(this).position().left;
//top side of button
var currentTopPosition = $(this).position().top;
var myToolTip = $(this).next();
myToolTip.css("top", (currentTopPosition + offTopSide) + "px");
myToolTip.css("left", (currentLeftPosition + offLeftSide) + "px");
myToolTip.show();
});
and this:
$(document).delegate('a', "mouseout", function () {
$(this).next().hide();
});
精彩评论