5

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?

1252748
  • 12,116
  • 27
  • 89
  • 197

3 Answers3

3

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

David Hellsing
  • 97,234
  • 40
  • 163
  • 203
0

You could:

var allEls = $('body *');

function isDisplayBlock(arr) {
    var isBlock = [];
    $.each(arr, function(i, e){
        if ($(e).css('display') === 'block') {
            isBlock.push(e);
        }
    })
    return isBlock;
}

But ive no idea how to check if they changed, instead of just checking if they are block.

dezman
  • 15,356
  • 8
  • 48
  • 82
0

You can just use $('div:visible') to check whether a div has display: block or display: none. Those are the only two values that :visible looks at anyway.

Source: How do I check if an element is hidden in jQuery?

-edit- I realise I didn't read thoroughly, you're asking about an event that tells you when display changed. There is none, see Nelson's comment on your question.

Community
  • 1
  • 1
Stephan Muller
  • 24,574
  • 14
  • 80
  • 119