As an exercise, I’m trying to make a hoverzoom script in Javascript without resorting to jQuery. The script puts all the <a> links on the page in an array, then searches for href with an extension of jpg and applies a hoverzoom function to it
I’m very close to getting it working. The function works fine for instances where the <a> filename DOES end in jpg, but when it ends in something different the code breaks. Here’s the offending code:
for (var i = 0; i < aLinks.length; i++) {
aExtensions[i] = aLinks[i].href.split('.').pop();
if (aExtensions[i].toLowerCase() == 'jpg') {
aImages.push(aLinks[i]);
}
aImages[i].onmouseover = function() {
hoverZoom(this);
}
aImages[i].onmouseout = function() {
refresh(this);
}
}
The full script plus a live version is here: http://james.is.agoodman.com.au/git/js_hoverZoom/
As you can see in the live demo it works for the two image links, breaks on the third non-image link, and then the subsequent image links don’t work either.
EDIT: Apologies, forgot to specify a question. How can I alter the script to only function when the source extension matches .jpg, and do nothing when the extension doesn’t match?
You need to move the event bindings into the
ifstatement:You aren’t always pushing an item to the
aImagesarray, soaImages[i]won’t always be something. Moving the event bindings into theifstatement and rearranging guarantees that the extension is “jpg”, and therefore binds an event to an existing item, then pushes it intoaImages