Determine the Element ID on MouseOver using jQuery

A user recently asked me if it was possible to determine the element id when the mouse was hovered over it. This requirement is quite simple using jQuery as demonstrated in the code here:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Find ID on Mouse Hover</title>
<
style type="text/css">
.sample
{
height:100px;
width:200px;
border: solid 1px black;
}
</style>
<
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() {
$('#para').html(this.id);
});
});
</script>
</
head>
<
body>
<
div>
<
div id='divOne' class="sample">
DIVONE
</div>
<
div id='divTwo' class="sample">
DIVTWO
</div>
<
div id='divThree' class="sample">
DIVTHREE
</div>
<
br />
<
br />
<
p id="para" />
</
div>
</
body>
</
html>

See a Live Demo



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

Jaan said...

But i dont c a practical usage of it...

Anonymous said...

Here is a practical usages for ya. You want to set a class effect of fade in/out.

$(".module").mouseover(function(){
...
});

But you dont want to fade in and out all of the objects of that class... so you use the id.

$("#' + this.id + '").animate({height:"150px"},"fast")';

Anonymous said...

... and i didn't fade at all in my code but you get the point. This page solved this problem for me. Thanks!