I can do this:
$("#icon").live("hover",
function()
{
var position = $(this).offset();
$('#popup').css({top: position.top - 10, left: position.left + 20}).toggle();
},
function()
{
$('#popup').toggle();
}
);
But this:
function show_popup(element)
{
var position = element.offset();
$('#popup').css({top: position.top - 10, left: position.left + 20}).toggle();
}
$("#icon").live("hover",
show_popup($(this)),
function()
{
$('#popup').toggle();
}
);
errors position is null on the page load.
Why does it run show_popup() on the page load? And what is wrong with that code?
This:
is a function call so it will be executed when
liveis being set up for execution, you want just a function in there. Whenshow_popup($(this))gets executed,thiswill probably bewindowandwindowdoesn’t have an offset, that means that yourpositioninsideshow_popupwill benulland there’s your error message. Also note that this approach tries to bind the return value ofshow_popup(which will beundefined) as a jQuery callback and that’s clearly not your intent.You want something like this:
Or perhaps this:
In this case you always have to supply the appropriate context when calling
show_popupso you’ll be doing a lot of things likeshow_popup.call(some_dom_element)if you want to callshow_popupanywhere that isn’t a jQuery callback.