0
<script type="text/javascript">
  $(function(){
    $('#example')[0].onmouseover = function(event) {
     alert("something");
    };
  });
</script>

<body>
<img id="example" src="example.jpg" " alt="ooooh! ahhhh!"/>
</body

Why do we need [0] behind example id ?

why it's not working if we remove [0] ?

3 Answers 3

3

Since you are calling native onmouseover you need to refer native DOM Element

$('#example')[0] // gives native DOM Element.

$('#example')[0].onmouseover=function(){}; //native event handling

If you remove [0] then you are referring jQuery object. So you need to use jQuery way of event handling

$('#example') //gives jQuery object
$('#example').mouseover(function(){}); //jQuery event handling
Sign up to request clarification or add additional context in comments.

Comments

0

Try

$(document).on("mouseover","#example",function(event) {
 alert("something");
};

Comments

0

.onmouseover is a JavaScript event handler and only applies to DOM elements. Since $('#example') is a jQuery object, onmouseover wouldn't do anything at all (not even produce an error).

However, each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get at the underlying element via $('#example')[0] which returns an element that onmouseover (and any other native JavaScript event handler) can work with.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.