How to delay invocation/execution of opacity (fadeTo) jQuery method on image/HTML element?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    How to delay invocation/execution of opacity (fadeTo) jQuery method on image/HTML element?



    Having responsive hover effects brings a dynamic feel to your web site, but you need to make sure that it is not too easy to accidentally invoke the hover function if a user accidentally hovers over the HTML element that invokes the effect, although sometimes it may be when a user is navigating around your website - such as moving their cursor back to the top navigation menu or something else (as you can clearly see in the screenshot above).

    To prevent this, we need to have a delay in place so the hover effect is not executed until the user is definitely over the HTML element and hasn't hovered over it for a split second to move to another area of the web page. I'm using the jQuery library here.

    Code:
    $(document).ready(function() {	
    	var timeOut;
    	var imgSelected;
    			
    	$('.slides-images-hover-pointer').hover(function()
    	{
    		imgSelected = this; // the imgSelected variable will contain the object that invoked the event
    		
    		timeOut = setTimeout(timeOutFunction, 500);
    	}, function()
    	{
    		clearTimeout(timeOut);
    		$(imgSelected).fadeTo('slow',1);
    	});
    	
    	function timeOutFunction()
    	{
    		$(imgSelected).prevAll().hide();
    		$(imgSelected).fadeTo('slow', 0.8);
    	}
    });
    Let's explain what each part of the code does.

    The variables that are declared at the top are so we can hold the setTimeOut function in a variable to disable it later on. The imgSelected variable holds the object that invokes the hover event so we can refer to the same object later on. With the hover() method (that is part of the jQuery library), the first parameter is the "hover in" event, and the second parameter (containing the clearTimeout() code) is the "hover out" event - all in one.

    If you notice in the timeOutFunction(), you'll notice the first line of code I am hiding all previous HTML elements using the slides-images-hover-pointer class. The reason being is because in my use case scenario, it prevents any prior HTML elements in a sliding transitional gallery from appearing behind the active image in the gallery when the opacity is reduced (i.e. using the fadeTo() method).

    The setTimeout() function works on milliseconds. The first parameter sets the function that is executed when the time specified in the second parameter has elapsed. The clearTimeout() function clears the timeout and subsequently prevents execution of the timeOutFunction() function.

    Hope this helps.
Working...
X