Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>$('div#imageContainer').on('mouseover', function(){ $(this).children('img').attr('src','../newImage.png'); }); </code></pre> <p>That'll do it. Doesn't matter where you put the code, as long as it's within the <code>$(document).load(function(){...});</code></p> <p>NOTE: this is using the latest jQuery 1.7.1 <code>.on()</code> function which is new to this version. Same thing can be accomplished with <code>.bind()</code></p> <p>Update for comments:</p> <p>If you want to keep this function in a separate file, you can wrap it in a function</p> <pre><code>function imageSwap(){ $('div#imageContainer').on('mouseover', function(){ $(this).children('img').attr('src','../newImage.png'); }); } </code></pre> <p>And then just call the <code>imageSwap()</code> function from within the document load.</p> <p>Also, if you want to use this on multiple divs with different images, you can do one of two things. Either A) name your images something like <code>img1_over.png</code> and <code>img1.png</code>, in which case you can modify the code as such:</p> <pre><code>$('div#imageContainer').on('mouseover', function(){ var img = $(this).children('img'); img.attr('src', img.attr('src').replace('.png', '_over.png')); }); </code></pre> <p>Or you can store the image path in a data attribute on the image themselves. In your HTML you would add the hover image to a data attribute like so:</p> <pre><code>&lt;img src="../cool_img.png" data-hover="../ever_cooler_image.png" /&gt; </code></pre> <p>And your code would look like this:</p> <pre><code>$('div#imageContainer').on('mouseover', function(){ var img = $(this).children('img'); img.attr('src', img.data('hover')); }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload