user2013160
user2013160

Reputation: 3

How can I pass and ID of an img to a function on mouseover?

I'm trying to pass an id of an img to a function on mouseover so that i can use this javascript on multiple images on one page?

i'm trying to change the img_id to whatever is being mouseovered

Can anyone please take a shot at this one?

Thanks!

<img 
src="http://coolimg2.1.jpg" 
alt="http://coolimg2."
onmouseover="animate();"
onmouseout="stopAnimation();"
id="myImg1" 
class="sample"
/>

<img 
src="http://coolimg3.1.jpg" 
alt="http://coolimg3."
onmouseover="animate();"
onmouseout="stopAnimation();"
id="myImg2" 
class="sample"
/>

<p id="test"></p>

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script> 

<script type="text/javascript">


        $(function() {
            $('.sample').mouseover(function() {
                $('#test').html(this.id);
            });
        });  



var myImages = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
var img_index = 0;
var timer;
//I'm trying to change the img_id to what is being mouseovered on. not "myimg2"
var img_id = "myImg2";
var imgsrc = document.getElementById(img_id).alt;
// Start animation
function animate() {
    me = document.getElementById(img_id);

    me.src = imgsrc + myImages[img_index] + ".jpg"

    img_index++;

    if (img_index == myImages.length){
        img_index = 0;
    }

    timer = setTimeout(animate, 500);
}

function stopAnimation() {
    clearTimeout(timer);
}
</script>

Upvotes: 0

Views: 668

Answers (1)

Undefined
Undefined

Reputation: 11431

Try changing your mouseover function to this:

$('.sample').mouseover(function() {
   img_id = $(this).attr('id');
   animate();
});

Here is a jsfiddle showing the paragraph tag changing to the ID of the mouseover element.

Upvotes: 1

Related Questions