tags:

views:

115

answers:

4

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?

+2  A: 

JavaScript:

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

HTML:

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

You do not need jQuery for this.

Jacob Relkin
Beat me to the punch! :)
Pekka
you do mean onmouseover instead of onclick, no?
Mark E
I've noticed that we usually answer the same types of questions, it's only a matter of who answers first. :)
Jacob Relkin
@Mark Yes, i do.
Jacob Relkin
How about upvoting because i had VALID html?? ( the `alt` attribute ) :)
Jacob Relkin
+1 for doing it without jQuery (*despite* the OP asking for it), and for having valid HTML... =)
Mark E
+1 for doing it without Jquery (which just uglifies the job horrendously. Just *look* at that code!) :)
Pekka
@Mark, thank you =)
Jacob Relkin
@Pekka, that's why i did it that way. Thanks!
Jacob Relkin
-1 for inline script attributes
redsquare
+3  A: 

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..

Mark E
but this code print "undefined"... :(
chalist
@chalist, sorry -- give it another go
Mark E
Why not just use `this` inside the handler instead of the actual '#bar' selector?
Jacob Relkin
like, `$('#bar').mouseover(function(){ alert($( this ).attr('src')); });`? Man, @Pekka is right, this is UGLY!
Jacob Relkin
@Jacob, started that way, OP was getting undefined, this will for sure return the correct result. rolled it back for good measure.
Mark E
+2  A: 
<img src="some_img.gif">
<script>
$("img").bind("mouseover",function(){
alert($(this).attr("src"));
});
</script>
Caleb
Why use `bind` when you have the `mouseover` shortcut function?
Jacob Relkin
but this code print "undefined"... :(
chalist
Good point. You don't really need jquery at all to do this
Caleb
A: 
$('img').mouseover(function() { 
    alert( this.src );
});
David