I’m using a very standard “one-page” model for JQueryMobile development like:
<div id="page1" data-role="page">Lorem Ipsum</div>
<div id="page2" data-role="page">
<div id="mycontent" data-role="content"></div>
</div>
When I click a link to navigate from page1 to page2, I’m appending content to $(“#mycontent”) that contains images that do not always have specified width/height, then I’m applying iScroll-4 so that I can scroll/zoom the content – in some cases I need to zoom it as soon as it is loaded so it fits nicely on a mobile screen (generally 600px wide to start). The problem is, once the images load, the formatting falls apart, particularly since I need to reposition the element, as CSS zoom likes to center the zoomed item, not align to top/left corner.
That was probably a long explanation for a simple problem (maybe there is a better way to do the above?), but here is my real problem: I’m trying to add an event listener for the load event on the div, so that I can check to see if I need to reposition the div once all the images are loaded:
$("#mycontent").addEventListener('load', doSomething(), false);
function doSomething(){ alert("something"); }
The crazy thing is, doSomething() DOES get fired, but then Safari throws the following error and crashes JQuery:
TypeError: ‘undefined’ is not a function (evaluating
‘$(“#mycontent”).addEventListener(‘load’, doSomething(),
false)’)
The element is present in the DOM, and it’s definitely loaded at the time the event listener is added – and I guess this is made clear by the fact that it fires. JQM applies some styles to the element as it is transitioning, but I don’t see how that would affect it.
Any help would be appreciated, as I’ve been banging my head against this for a while and am about to write some very ugly looping hacks to check for size changes :/
There are two possible issues. The second parameter of addEventListener should be a function, not a function call:
element.addEventListener("load", doSomething, false);. In your code thedoSomething()is executed whatever the event name is.Also,
$('#mycontent')returns an array of elements which I think causes your TypeError, so you might want to use:JQuery also has load() which might work, if you listen to each image’s load event and adjust your layout:
This will fire once for each image, so you might want to keep a count if you know the number of images, or else create / reset a timeout on each load, and after the timeout call doSomething.