I need a bit of help again… I have this code:
<div id="lyrics">
<div id="lyricsClose"></div>
<div id="ajax-content"></div>
</div>
id lyrics and lyricsClose are hidden. I basically want an overlayed div that shows lyrics, with a close button on the top, right. So, with jQuery:
$(document).ready(function() {
$('[id^=showContent]').click(function(e) {
e.preventDefault(); // Prevent link acting as link
$("body").append("<div id='lyricsOverlay'></div>");
$("#lyricsOverlay").height($(document).height());
$('#lyrics').css("display", "table");
$('#lyrics').hover(function() {
$('#lyricsClose').toggle();
});
$('#lyrics').mouseleave(function() {
$('#lyricsClose').css("display", "none");
});
$('#lyrics').show(); // Show content layer
$('#lyricsOverlay').click(function() {
$('#lyrics').hide();
$('#lyricsOverlay').remove();
});
$('#lyricsClose').click(function() {
$('#lyrics').hide();
$('#lyricsOverlay').remove();
});
});
})
When clicking:
Works fine, BUT, only sometimes. First time clicking works perfectly, second time lyricsClose div dissapears and does not show. Third time OK again, fourth KO, …
I suppose something is wrong in my jQuery code… Can’t se what it is…
Thanks!
You are constantly re-binding the
hoverandmouseleaveevents.As the
hoverevent callstoggleit calls it for every binding, couter-acting the previous execution.Unbinding the events before re-binding should fix it.
Also, as you already set the display value of
#lyrics.show()is redundant.DEMO – Unbind before re-binding