Is there any way to listen for elements being shown or hidden?
I would like categorically to--whenever an element goes from hidden to shown--put focus on the first input element within the newly shown element
I thought of attaching a click event to everything and putting it at the top of the document, thinking that would trigger before anything and I could track whether the clicked element's next("div")
(or something) would have a css display property of none
, then setting a small timeout, then setting the focus, but I get undefined
when I try to access that CSS property
$("html").on("click", "body", function(){
alert($(this).next("div").css("display")); //undefined
});
Is there a way to do this?
You can try something like this (it’s kind of a hack). If you monkey-patch the css/show/hide/toggle prototypes in jQuery, you can test if the element changes it’s :hidden
attribute after a "tick" (I used 4ms). If it does, it has changed it’s visibility. This might not work as expected for animations etc, but should work fine otherwise.
DEMO: http://jsfiddle.net/Bh6dA/
$.each(['show','hide','css','toggle'], function(i, fn) {
var o = $.fn[fn];
$.fn[fn] = function() {
this.each(function() {
var $this = $(this),
isHidden = $this.is(':hidden');
setTimeout(function() {
if( isHidden !== $this.is(':hidden') ) {
$this.trigger('showhide', isHidden);
}
},4);
});
return o.apply(this, arguments);
};
})
Now, just listen for the showhide
event:
$('div').on('showhide', function(e, visible) {
if ( visible ) {
$(this).find('input:first').focus();
}
});
Tada!
PS: I love monkeypatching
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With