I am using this code the create an onshow event:
(function($){
$.fn.extend({
onShow: function(callback, unbind){
return this.each(function(){
var obj = this;
var bindopt = (unbind==undefined)?true:unbind;
if($.isFunction(callback)){
if($(this).is(':hidden')){
var checkVis = function(){
if($(obj).is(':visible')){
callback.call();
if(bindopt){
$('body').unbind('click keyup keydown', checkVis);
}
}
}
$('body').bind('click keyup keydown', checkVis);
}
else{
callback.call();
}
}
});
}
});
})(jQuery);
Then I’m calling it:
$(document).ready(function(){
$('.mydiv').onShow(function(){
alert('myDiv is now showing');
});
});
I’m also toggling the link which triggers the div to show and hide:
$('.myLink').click(function(){
$(".mydiv").slideToggle();
});
and finally here is the html:
<a href="#" class="myLink">Step 1</a>
<div class="myDiv">content here</div>
The problem is that the alert is only showing once when I click the link after the page is loaded. If I click it again I won’t show.
Any ideas why?
I think this is a misunderstanding of how events work in javascript. What your custom extension is doing is running once. The line
$('body').bind('click keyup keydown', checkVis);listens for the click keyup and keydown events, but this listener is only applied to elements that are hidden and have passed theif($(this).is(':hidden')){check.So if the element in question starts off hidden, it will respond with
checkVison ‘click keyup and keydown’, but that is the only instance in which anything would run afteronShowextension finishing running the first time..slideToggle();does not fire any events by default, so your extension cannot listen for such an event to fire.The closest you can get to listening for an element changing its visibility would be to use something like the dom mutation event, but that has be deprecated and is not cross browser supported.
If you really need the ability to run an extension whenever an element is “shown” by jQuery the best way I can think of would be to extend the jQuery functions you wish to use to fire a custom event, which would looks something like this:
Then you can do this:
Or to continue your extension strategy:
This way it will run the first time, and then re-run whenever the new ‘customOnShowEvent’ is fired (“triggered”).