Ryan Gillies
Ryan Gillies

Reputation: 463

Jquery onmouseover triggers on second event

I've created the following function in Jquery

function menuItem(x,i) {
var imgALT = $(x).text();   
$(x).mouseover(function()
{
    $(x).parent().parent().parent().children("img").attr("src", "menu/menu"+i+".jpg");
    $(x).parent().parent().parent().children("img").attr("alt", imgALT);
    $(x).parent().children("span").css("color", "#FFFFFF");
    $(x).css("color", "#CA0109");
});
};

And I trigger it using the following:

<span onmouseover="menuItem(this,'09-01')">月亮蝦餅 (2份)</span>

It works exactly as I intend it to, but only after I mouseover the span for the second time, not the first. I assume this is perhaps a loading issue of some kind? How should I go about ensuring it triggers on the first mouseover, as well as subsequent events?

Many thanks!

Upvotes: 0

Views: 596

Answers (2)

Blender
Blender

Reputation: 298326

The problem is that you're binding the event using jQuery only after you've hovered over the element and the inline onmouseover has fired.

Since it looks like that onmouseover event is critical to your application's structure, change your JavaScript to something like this:

function menuItem(x,i) {
    var $x = $(x);
    var imgALT = $x.text();

    $x.parent().parent().parent().children("img").attr("src", "menu/menu"+i+".jpg");
    $x.parent().parent().parent().children("img").attr("alt", imgALT);
    $x.parent().children("span").css("color", "#FFFFFF");
    $x.css("color", "#CA0109");
}

Ideally, I would use data- attributes:

HTML:

<span data-image="09-01">月亮蝦餅 (2份)</span>

JavaScript:

$(document).ready(function() {
    $('span[data-image]').mouseover(function() {
        var $this = $(this);
        var $images = $this.parent().parent().parent().children("img");

        $images.attr("src", "menu/menu" + $this.data('image') + ".jpg");
        $images.attr("alt", $this.text());

        $this.siblings("span").css("color", "#FFFFFF");
        $this.css("color", "#CA0109");
    });
});

Upvotes: 3

Buzz
Buzz

Reputation: 6330

Use document.ready function

$(document).ready(function(){
  $('span').mouseover(function(){});
    });

Upvotes: 1

Related Questions