Samir Memmedov
Samir Memmedov

Reputation: 147

jquery onmouseover and onmouseout not working with IE

the following code works fine with Opera but not with IE 8

I have dtest2 div element on page, for testing purpose I am trying to change the content of div element on mouseover and mouseout events of an image.

html:

  <a ><img  title='' class='imgclass' src='images/image1.jpg'  onmouseover="f1('1')"  onmouseout="f2('1');"    ></a>

Jquery :

function f1(id)
{   

 $('#dtest2').html("Test "+id);
}
    function f2(id)
{   
        $('#dtest2').html("Test 2 "+id);
}

with Opera it works normal. With IE it works 1 time or few times, then stops working. any specific command for IE ?

These images are coming from database, id is there unique number from database .

Thanks

Upvotes: 0

Views: 610

Answers (1)

KRyan
KRyan

Reputation: 7618

You're mixing your idioms here a little bit. It should still work, but you'll probably have better results (and definitely neater code) by doing things the "jQuery way," which involves separating code from the HTML.

So, first the HTML:

<a>
    <img title='' class='imgclass' src='images/image1.jpg'>
</a>

It's the same as what you had, without the onMouseOver and onMouseOut attributes.

Now, the jQuery, preferably in a separate file that you use <script src="url.js" type="text/javascript"></script> to load in.

$('img.imgclass').hover(function() {
    $('#dtest2').html('Test');
}, function() {
    $('#dtest2').html('Test2');
});

One of the major advantages of jQuery is that it is designed to smooth all browser incompatibilities so that you just need one code for all browsers.

As for the id that you want to pass to your function, that's a little trickier. Where is that number coming from and what does it mean? That will affect how to handle that.

If nothing else, you can include it in your HTML with an HTML5 data- attribute, like so:

<a>
    <img title='' class='imgclass' src='images/image1.jpg' data-hover-id="1">
</a>

You can then retrieve it with the following change to the jQuery:

$('img.imgclass').hover(function() {
    var id = $(this).data('hover-id');
    $('#dtest2').html('Test ' + id);
}, function() {
    var id = $(this).data('hover-id');
    $('#dtest2').html('Test2 ' + id);
});

EDIT for edited question: Since they're unique IDs coming from the database, it probably makes sense to just use them as the id of the img. However, you should not use purely-numerical ids. So whatever you're using to pull the ID from the database should prepend something, perhaps just i or img.

Then your HTML will look like

<img id="i1" title="" src="images/image1.jpg">

And your jQuery can access that with $(this).attr('id') instead of $(this).data('hover-id').

Upvotes: 1

Related Questions