Question

I have the following divs:

<div id="foo">
...
    <div id="bar" class="container hidden">
    ...
    </div>
</div>

I use Twitter Bootstrap 3 and I added the hidden class to automatically hide the second div by default.

I have the following code:

$(document).ready(function() {
    $("#foo").hover(
        function() {
            $("#bar", this).toggleClass("hidden");
        }, function() {
            $("#bar", this).toggleClass("hidden");
    });
});

It seems to work correctly BUT if the mouse if already hover the #foo div during the page load, it applies by default the hover effect. After that if I move the mouse outside the #foo div, it applies again the toggleClass and displays the inner #bar div.

How to prevent this behaviour on page load?

Was it helpful?

Solution 2

No one mention it but hover pseudo event accept in/out handler, so you could toggle class:

$("#foo").hover(function () {
    $("#bar").toggleClass("hidden");
});

And as IDs must be unique on document context, no need to pass context, just target element with ID.

OTHER TIPS

This is a proper way to do it:

$("#foo").hover(
    function() {
        $("#bar", this).addClass("hidden");
    }, function() {
        $("#bar", this).removeClass("hidden");
});

Instead of using toggleClass() try using addClass() and removeClass():

$("#foo").hover(

    function() {

        $("#bar", this).addClass("hidden");
    }, function() {

        $("#bar", this).removeClass("hidden");
});

This way allows you to have a more precise control over the elements.

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