Reputation: 95
I am facing a strange bug at the moment, involving javascript. I have used jquery ui tabs to dynamically add and remove tabs in my website, the content of the tab contains two buttons which upon mouseover dissappear and become visible on mouseleave of the relevant link at the bottom. This mouseover is working fine for the first default tab but not for dynamically added tabs. when i mouseover the content of the new tab the effect is not happening. Here is a fiddle
http://jsfiddle.net/Hunain/E2nJa/ this fiddle is not exact as my result and doesn't contain my issue so please read my above statement correctly, because i have explained the issue i have used following code for mouseover
$("#butt").mouseenter(function () {
$("#butt").css("visibility","hidden");
})
$("#info").mouseleave(function () {
$("#butt").css("visibility","visible");
});
Upvotes: 0
Views: 1253
Reputation: 36531
use on
delegated events...
$(document).on("mouseenter", "#butt", function () {
$(this).css("visibility","hidden");
});
$(document).on("mouseleave", "#butt", function () {
$(this).css("visibility","visible");
});
you can read through this post if you want to know more about on
direct and delegated event
it is better if you delegate it to closest static element that is present in the document rather than to document
or body
for better performance
Upvotes: 1
Reputation: 5989
with reference to your fiddle...
$("#butt").mouseenter(function () {
$("#butt").css("visibility", "hidden");
})
it should be like this
$jQuery.on("mouseenter","#butt",function () {
$("#butt").css("visibility", "hidden");
});
Same goes for other elements which you know are going to be added at runtime.
Upvotes: 1
Reputation: 323
You are binding the event on document load and adding button after the binding the event. So event will not bind with the element which added later.
You should bind event after adding buttons.
Upvotes: 3
Reputation: 56429
That's because mouseenter
and mouseleave
only work for items that exist in the DOM on page load
You need to use a delegated event: on
for jQuery 1.7+, or delegate
for earlier versions.
Try this (on
):
$("body").on("mouseenter", "#butt", function () {
$(this).css("visibility","hidden");
});
$("body").on("mouseleave", "#butt", function () {
$(this).css("visibility","visible");
});
Or this for pre-1.7 (delegate
):
$("body").delegate("#butt", "mouseenter", function () {
$(this).css("visibility","hidden");
});
$("body").delegate("#butt", "mouseleave", function () {
$(this).css("visibility","visible");
});
Upvotes: 1