0

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!

2 Answers 2

3

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"); }); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

I was just going to add an answer with this method instead! Got there too quickly! :)
1

Use document.ready function

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.