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?
views:
115answers:
4
+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
2010-01-24 02:51:16
Beat me to the punch! :)
Pekka
2010-01-24 02:52:29
you do mean onmouseover instead of onclick, no?
Mark E
2010-01-24 02:54:03
I've noticed that we usually answer the same types of questions, it's only a matter of who answers first. :)
Jacob Relkin
2010-01-24 02:54:20
@Mark Yes, i do.
Jacob Relkin
2010-01-24 02:54:51
How about upvoting because i had VALID html?? ( the `alt` attribute ) :)
Jacob Relkin
2010-01-24 02:59:51
+1 for doing it without jQuery (*despite* the OP asking for it), and for having valid HTML... =)
Mark E
2010-01-24 03:24:18
+1 for doing it without Jquery (which just uglifies the job horrendously. Just *look* at that code!) :)
Pekka
2010-01-24 03:29:51
@Mark, thank you =)
Jacob Relkin
2010-01-24 03:29:51
@Pekka, that's why i did it that way. Thanks!
Jacob Relkin
2010-01-24 03:30:38
-1 for inline script attributes
redsquare
2010-01-24 09:38:20
+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
2010-01-24 02:52:21
Why not just use `this` inside the handler instead of the actual '#bar' selector?
Jacob Relkin
2010-01-24 03:29:08
like, `$('#bar').mouseover(function(){ alert($( this ).attr('src')); });`? Man, @Pekka is right, this is UGLY!
Jacob Relkin
2010-01-24 03:32:04
@Jacob, started that way, OP was getting undefined, this will for sure return the correct result. rolled it back for good measure.
Mark E
2010-01-24 03:38:05
+2
A:
<img src="some_img.gif">
<script>
$("img").bind("mouseover",function(){
alert($(this).attr("src"));
});
</script>
Caleb
2010-01-24 02:55:14