I need some assistance with some javascript/jquery I have put in place. The function of this client side script is to set an event handler of all images within a particular selector on a page and if the image doesnt load (eg. not found), then its removed. My client side script is as follows, triggered in the document.ready of the external javascript file.
$('.imagecontainer').error(function() { ($this).parent().hide(); });
This works, sometimes! Sometimes when the page loads it works correctly, more time it works correctly for some images but the majority of the time it doesnt work at all. What it does if the image doesnt load, the surrounding anchor tag ie. the images parent is hidden. I have included alerts in the function to check when its called and it is triggered sometime but not all the time.
So I am wondering where I am going wrong. The path/src of the image is set in server side code by C# as the path is derived on the server side and cant be changed.
Any tips or ideas on this? I read somewhere that this event should be bound prior to the source of the image is set but not sure if this is achievable as the source of the image is set in the server side.
Once I have this resolved (hopefully), I have another problem. Some of the image are dynamically loaded by a user action and are not present on the page at run time. I have got around this for 99% of events by using the jquery syntax .live(‘click’, function) etc. Does anyone know if I can do similar with the .error or how I can set it up.
A couple things to note:
Your snippet there has a syntax error. You have
($this).parent().hide();instead of$(this).parent().hide();.Review the .error() documentation. Specifically, there were two things I noted. First is the observation that the call may not work properly if you are running locally. Second, in the comments, someone observed the following:
Based on the small snippet you provided, it looks like you might be targeting an element that contains an image, rather than the image itself. This may very well be the source of your problem.