Search code examples
jquerymouseenter

mouseenter rollover effect only works after second entry


I've tried to find similar posts on this specific matter with little success so hopefully someone a little more experienced with JQuery could shed light on my problem. I'm currently working on a portfolio site, i.e. alot of images. I wanted to make a Jquery rollover effect when you hover above one of the thumbnail images presented on the site.

The effect itself has been achieve but it comes with a sort of bug. Whenever I refresh the page or view the page anew, whenever I my mouse enters the image container element which should trigger the Jquery effect, it doesn't do so the first time, but when I try it a second time without refreshing the page, the effect is there.

Here is the basic html markup:

<section class="main">
    <div class="wrapper">
        <article class="ImageContainer">
             <a href="#">
                 <img class="back" src="Images/Image1.jpg" alt="Image1"/>
                 <span class="over" style="display: none;">
                     <h2>Title</h2>
                     <p>Watch Project</p>
                 </span>
            </a>
        </article>
    </div>
</section>

So as you can see I've solved my "rollover effect" with a "display: none" solution which I later let my Jquery code "fadeIn" to make it visible on the mouseenter effect.

Below is the CSS for span class="over", probably not necessary to show but just incase.

.over {
    width: 300px;
    height: 300px;
    background-image:url(Images/over.png);
    position: absolute;
    top: 0px;
    left 0px;
}

And now for my JQuery

$(document).ready(function(){       
    $(".ImageContainer").mouseenter(function(){
        $(this).children('a').children('span').fadeIn(200);
    });
    $(".ImageContainer").mouseleave(function(){
        $(this).children('a').children('span').fadeOut(200);
    });
});

It seems the problem only arise when viewing it in a browser, this jsfiddle seems to work without issue. I am at loss as to why. All my links to my other documents also work and I have jquery and jquery UI linked.

http://jsfiddle.net/LRdR9/

SOLUTION TO MY PROBLEM: my .over class didn't have "display: block;" which caused the browser to not see it. Upon second mouseenter it automatically put it there itself. It tricked me thinking I had another issue.


Solution

  • Everything seems to work in jsFiddle.

    Note that in your jsFiddle you are running your code onload - make sure you're doing that in your file itself (be sure to place your jQuery inside the body, not the head). Also, make sure you're testing it in multiple browsers.

    P.s. You could shorten your code to the following.

    $(document).ready(function(){    
       $(document).on('mouseenter mouseleave', '.ImageContainer', function () {
            $('a > span', this).fadeToggle(200);
       });
    }):
    

    Example jsFiddle.