0

I'm trying to detect whether an element is visible after the DOM is ready. This element is a third party widget that loads slower than the page does.

My console.log for 'dom ready' is firing - like it should, but my check to see if the element is visible is returning false, as the element loads after the dom is ready.

Is there a way to listen for elements after the dom has loaded?

<script>
    $(function(){
        console.log('dom ready');

        if($(element).is(':visible')){
            console.log('element is visible. do stuff.');
        }

    });
</script>
Blexy
  • 9,573
  • 6
  • 42
  • 55

2 Answers2

1

you can get the id from the iframe, or from the document that is being loaded and do something like this..

$('#external').load(function(){
    //lets do something when is loaded
    if($(element).is(':visible')){
       console.log('element is visible. do stuff.');
    }
});

This will trigger once that script, iframe is done loading

Jorge Y. C. Rodriguez
  • 3,394
  • 5
  • 38
  • 61
1

Try to read a documentation, maybe third-party widget's API allows you to attach listener on create event. That would be an ideal solution.

If it is not possible try using setTimeout function:

$(function(){
    console.log('dom ready');
    setTimeout(function() {
        if($(element).is(':visible')){
            console.log('element is visible. do stuff.');
        }
    }, 10);
});

If 10 ms is not enough, you may increase this interval unless it works, although I don't recommend using this approach.

Oleg
  • 22,300
  • 9
  • 68
  • 84