Ok So I'm trying to run some javascript whenever theres an issue loading an image provided by an ad network.
The ads are showing fine but my scripts are getting called anyway. Am i going about this the wrong way?
code:
<script type="text/javascript">
function catchAdLoadError(i) {
console.log("error happened loading advert " + i);
trackingInfo['adfailedtoload'] = 'testad' + i;
document.getElementById("t-tracking-fragment").innerHTML = vsDoTracking();
}
$(function() {
document.getElementById("advertBanner0").addEventListener("error", catchAdLoadError(0));
document.getElementById("advertBanner1").addEventListener("error", catchAdLoadError(1));
});
</script>
Your error function is being called and interpreted when you are setting the event listener. Use an anonymous function to define the event listener:
document.getElementById("advertBanner0").addEventListener("error", function(){ catchAdLoadError(0) } );
instead of :
document.getElementById("advertBanner0").addEventListener("error", catchAdLoadError(0));
the same for the second event listener.
Notes:
The function addEventListener expects parameters in this format:
addEventListener( eventName, callbackFunction )
When you specify some function to listen an event, the 2nd parameter expected is a function object, not a function call, so catchAdLoadError(0)
executes immediately. You could put a function name directly like catchAdLoadError
but since you need an exta parameter in the function call (0 or 1), you must put each specific call in an anonymous function that will be called by the event.