Juan David
Juan David

Reputation: 247

Mouseover image stays the same

I have a problem with this code I'll explain a little how this works,

The idea of this is that when hovering in tag (a), change the image of the id="meal", by the one that is in the (data-meal = "meal-14") .. in a few words

The pre-determined image is meal-0.png, hover in tag (a) with (data-meal = 14), replaces the url of the image with (meal-14.png),

Everything works fine, I only have one problem and is that when you stop hovering, do not go back to the pre-determined image, it stays in the image that became hover. Should return to the image meal-0.png.

 <div class="imagen-hover" id="meal">
        <img src="/public/tienda/meal-0.png" alt="">
    </div>  

    <ul>
<li><a class="carne-a" data-meal="meal-14">14. Punta de Anca</a></li>
<li><a class="carne-a" data-meal="meal-16">16. Chata Angosta</a></li>
    </ul>


jQuery(document).ready(function($) {

            var path = "/public/images/";
            $(".meal-a").on("mouseover", function() {
                var meal = $(this).attr("data-meal") + ".png";
                $("#meal img").attr("src", path + meal)

            });
});

Upvotes: 0

Views: 45

Answers (2)

Scott Selby
Scott Selby

Reputation: 9580

that is because it is doing exactly what you told it to do.

you need to make another event handler for mouseleave

or you can look at the jQuery docs , mouseenter can take two call backs , one for entering and one for leaving

        $(".meal-a").mouseenter( function() {
            var meal = $(this).attr("data-meal") + ".png";
            $("#meal img").attr("src", path + meal)

        }).mouseleave( function() { //for when mouse leaves
            });

What I would recommend though... you do not need javascript or jQuery at all for this , there is a css selector for while the user is hovering over an element

 .meal-a{ // regular code
  }
 .meal-a:hover{ // hover code
 }

Upvotes: 5

SED
SED

Reputation: 311

Also add a "mouseout" function to handle returning the image to its previous value

$(".meal-a").on("mouseout", function() {
     $("#meal img").attr("src", "meal-0.png")
});

Upvotes: 2

Related Questions