1

I have a modal dialog that is opened when user clicks in a button. It must be dynamic. It has a lot of images from external sources, e.g. <img src="http://example.com/image.jpg">. After this modal is opened I want to sum the height of all images loaded. So I'm calling imageCalculation() in onShow

    <p:dialog 
        id="myDialog" 
        widgetVar="myDialogWV" 
        modal="true"  
        dynamic="true"
        onShow="imageCalculation(); ">

        <ui:include src="/somePage.xhtml"  />

    </p:dialog>

<script type="text/javascript">
    function imageCalculation(){
        var total = 0;
        $.each($('#form\\:myDialog').find('img'), function(k,v){
            total += v.naturalHeight;
        });
        alert(total);
    }
</script>

The problem is that at the moment imageCalculation() is called, the images haven't been loaded from external sources yet, and naturalHeight is still 0.

Is there a way to run a javascript after all the dialog content is completely loaded?

EDIT: The content from somePage.xhtml is populated by a p:dataGrid that gets HTML code pieces from DB. Some of these codes are <img... So theoretically I can't change them

Thanks

qxlab
  • 1,506
  • 4
  • 20
  • 48
  • Since image loading is asynchronous you will have to bind load event handlers to each and track when they have all loaded. Should find lots of similar posts here to help – charlietfl Jun 26 '16 at 21:10
  • thanks I have found a solution will post it – qxlab Jun 26 '16 at 21:19

2 Answers2

3

I've found a plugin to help me: waitForImages jQuery plugin

$('selector').waitForImages(function() {
    alert('All images are loaded.');
});
Community
  • 1
  • 1
qxlab
  • 1,506
  • 4
  • 20
  • 48
0

I'm not sure but you can try to add onload attribute to all pictures.
Like this:

<script>
function loadHandler(x) {
     console.log(x+" element loaded!");
}
</script>
<img src="img1.png" onload="loadHandler('1 image')">
<img src="img2.png" onload="loadHandler('2 image')">
//etc...

Then you can count pictures for loading and already loaded ones in loadHandler()

NulledCoder
  • 265
  • 2
  • 15
  • Thanks but I can't change those images code... is there any other way? – qxlab Jun 26 '16 at 21:16
  • This still tricky since you have no tracking for all to complete. Using inline event handler not nearly as easy to do this as external one created in a loop – charlietfl Jun 26 '16 at 21:24