azamsharp
azamsharp

Reputation: 20086

Image Tag OnMouseOver Not Fired

I have very simple code and I am not sure why the Foo function is not fired when the mouse is over the image:

here <img id="sss" alt="some image" onmouseover="Foo(this);" src="https://www.google.com/intl/en_com/images/srpr/logo3w.png" width="16" height="16"   />

<div onmouseover="Foo(this);"> 
    THIS IS DIV
</div>

function Foo(obj) 
{
    alert('s');
}

UPDATE 1:

What actually happens is that I create the image element dynamically and then add it to the page. The Foo function is already inside the JS file but it never gets called.

Upvotes: 1

Views: 530

Answers (3)

Charlie G
Charlie G

Reputation: 824

EDIT: Nothing is wrong with the code as long as you have the script included in the <head>

try it: jsfiddle

Upvotes: 1

Wayne
Wayne

Reputation: 60424

If that's your actual code then the only issue is that you need to wrap the JavaScript in a <script>:

<script>
function Foo(obj) {
    alert('s');
}
</script>​

See a demo:

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83366

The code you have currently is correct, as this fiddle shows. I'm guessing your problem is that Foo is not global on your page.


Also, instead of passing this as a parameter to your function, you can set it as the this value inside of your function by using call

onmouseover="Foo.call(this);"

function Foo()  {
    alert(this.src); //this is the img you just mouse-overed 
}

Finally, consider changing Foo to foo, since functions starting with capital letters usually denote constructors in JavaScript.

Upvotes: 2

Related Questions