Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listen for any div that goes from display: none to display:block

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?

like image 290
1252748 Avatar asked Oct 21 '22 23:10

1252748


1 Answers

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

like image 119
David Hellsing Avatar answered Oct 24 '22 13:10

David Hellsing