matt136 matt136 - 1 year ago 73
Javascript Question

jQuery hover() - Visual Issue When Mouse Runs Over Image

Hey I'm very new to jQuery with little programming knowledge so please bear with me on this.

I created a script that will fade between two images on hover. The issue is that the fade effect continues if the cursor isn't hovering the image which means that if a user simply passes their cursor through the image whilst travelling to an alternative destination, they will see the full fade effect. Also if a user passes their cursor over the image multiple times, the fade effect will show multiple times.

Please see the image at the bottom of the page here:

Please see my jQuery below:

var imgelement = "#element"; /* Element containing the original image */
var hoverimageurl = ""; /* Image URL of the hover image */

jQuery(document).ready(function() {

/* Add CSS and a class to the original image to fix positioning and give it an identification */
jQuery(imgelement + " img").addClass("originalimage").css("position", "relative");

/* Prepend hover image to the element. Set the SRC to the hover image URL */
jQuery(imgelement).prepend('<img class="hoverimage" style="position: absolute; width: 100% !important; height: 100% !important;" src="' + hoverimageurl + '">');

/* Fade out original image and fade in hover image on hover */
jQuery(imgelement).hover(function() {
jQuery(imgelement + " .originalimage").fadeTo(1000, 0);
jQuery(imgelement + " .hoverimage").fadeTo(1000, 1);
}, function() {
jQuery(imgelement + " .hoverimage").fadeTo(1000, 0);
jQuery(imgelement + " .originalimage").fadeTo(1000, 1);


Could anybody please advise what I need to do to avoid this from happening? Thank you very much for your help.

Answer Source

use .stop( true) to stop any currently-running animation on the matched elements.

jQuery(imgelement + " .hoverimage").stop( true).fadeTo(1000, 0);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download