1

When the mouse cursor moves over an image, I would like to display an alert() containing the value of that image's src attribute. How could I go about accomplishing this?

4 Answers 4

4

You can use the mouseover event.

If you have

<img src='foo.jpg' id='bar'>

You can have some jQuery code like

$('#bar').mouseover(function(){ alert($(this).attr('src')); });

(if this fails you could also try replacing $(this) with $('#bar'), but as noted in the comments it's pretty ugly)

edit: missed the need to display the src attribute first time through..

Sign up to request clarification or add additional context in comments.

4 Comments

@chalist, sorry -- give it another go
Why not just use this inside the handler instead of the actual '#bar' selector?
like, $('#bar').mouseover(function(){ alert($( this ).attr('src')); });? Man, @Pekka is right, this is UGLY!
@Jacob, started that way, OP was getting undefined, this will for sure return the correct result. rolled it back for good measure.
2

JavaScript:

function alertSource( image ) {
   alert( image.src );
}

HTML:

<img src="path/to/image" onmouseover="alertSource(this);" alt=""/>

You do not need jQuery for this.

5 Comments

you do mean onmouseover instead of onclick, no?
I've noticed that we usually answer the same types of questions, it's only a matter of who answers first. :)
How about upvoting because i had VALID html?? ( the alt attribute ) :)
+1 for doing it without jQuery (despite the OP asking for it), and for having valid HTML... =)
+1 for doing it without Jquery (which just uglifies the job horrendously. Just look at that code!) :)
2
<img src="some_img.gif">
<script>
$("img").bind("mouseover",function(){
alert($(this).attr("src"));
});
</script>

1 Comment

Why use bind when you have the mouseover shortcut function?
0
$('img').mouseover(function() { 
    alert( this.src );
});

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.