Change the image source on rollover using jQuery
Here's a quick solution to change an image's source on mouseover using jQuery. Bind the hover() event on the image and alternate its src attribute. Use the attr() method for updating src:
Swap new-image.jpg
and original-image.jpg
with your actual image paths. The $('#image')
is jQuery's way of selecting the image using its id.
Dealing with multiple images
If multiple images are present, we need a more general solution. The golden ticket here is the data-other-src
attribute. Use it to store the rollover image source for every single image:
Next, swap the images using this:
This piece of genius lets you handle rollover for numerous images using just a single event handler. Efficiency level? 1000!
Lights instant on: Preload images
For a stoic transition between images, it's a good idea to preload the rollover images. This ensures smooth changeover without annoy blinking.
Incorporating this in the $(function() {})
handler ensures the preload happens right off the block when the page loads.
Master handling with CSS and Sprites
Why use JavaScript when CSS can handle it?
CSS can handle rollovers quite efficiently with the :hover
pseudo-class:
Taking this route might improve performance as it's tapping into the browser's native capabilities.
Sprites - Combine, then divide
Using sprite sheets is like putting all your clothes in one suitcase. All states of an image are in one file, and the image element's background-position gets a makeover on hover. This could lead to fewer server requests and a quicker page load time.
Accessibility and responsiveness
Remember to test your hover effects on various devices. Screen readers and keyboard navigation should not face hurdles because of your cool hover effects. Accessibility as cool as hover effects!
Follow up, Document and Dominate
For long-term peace, keep your code documented and modular. If your project is based on jQuery, ensure your code plays well even when JavaScript is disabled.
Ensure your image paths are valid and preload your rollover images to eradicate broken links or delayed loading.
Was this article helpful?