Question

I have 3 groups of divs which have a class dynamically assigned to them. When a user hovers over any of the divs, jQuery checks the class and fades the others with the same class. This works well but if I hover between the divs with the same classes the jquery seems to fire every time. Presumably because its re-checking the class and firing the effect.

My question is how can I stop the flicker when hovering between the same class divs?

The divs are all floated left with 1px margin. (I've tried removing the margin BTW).

My markup:

<div id="projects">

   <div class="p-1">IMAGE</div>
   <div class="p-1">IMAGE</div>
   <div class="p-1">IMAGE</div>

   <div class="p-2">IMAGE</div>
   <div class="p-2">IMAGE</div>
   <div class="p-2">IMAGE</div>

   <div class="p-3">IMAGE</div>
   <div class="p-3">IMAGE</div>
   <div class="p-3">IMAGE</div>

</div> 

And the jQuery

    $('#projects div[class^=p-]').hover(function() {
        $('#projects div[class=' + $(this).attr('class') + ']').fadeTo(200, 0.2, function() {
        });
    }, function() {
        $('#projects div[class=' + $(this).attr('class') + ']').fadeTo(200, 1.0, function() {
        });
    });

And a fiddle: Fiddle

Was it helpful?

Solution

I've updated your fiddle. Adding the stop() function should be enough for what I understood from your comments:

$('#projects div[class^=p-]').hover(function() {
    $('#projects div[class=' + $(this).attr('class') + ']').stop().fadeTo(0, 0.2, function() { });
    }, function() {
        $('#projects div[class=' + $(this).attr('class') + ']').stop().fadeTo('slow', 1.0, function() { });
    });

http://jsfiddle.net/hXHGe/9/

This functions stops any previous anymation. Since the hover in is prior to hover out it will stop the running animations and force it to remain faded to 0.2

OTHER TIPS

It seems as you hover in between your individual div elements, the cursor is placed over a spot outside of your div class triggering the fade. As you continue to hover down the list of elements, the flickering effect becomes more obvious.

One way would be to restructure your markup so that the .p-# div is a parent div to those images so the hover effect is applied once to the child div elements, like so,

<div id="projects">

   <div class="p-1">
       <div>IMAGE</div>
       <div>IMAGE</div>
       <div>IMAGE</div>
   </div>

   <div class="p-2">
       <div>IMAGE</div>
       <div>IMAGE</div>
       <div>IMAGE</div>
   </div>

   <div class="p-3"> 
       <div>IMAGE</div>
       <div>IMAGE</div>
       <div>IMAGE</div>
   </div>

</div>

The individual children div elements could have unique identifiers if need be, but this will eliminate the flicking effect you are now seeing.

You can preview the code at this jsfiddle

The above fiddle was merely a demonstration, but with more information we could devise a better way to meet your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top