Reputation: 42753
I have div tag (id=div_1), this tag has several neighbor elements, after on moseout on this tag, mouse is over already on other elements right? I want at onmouseout on div_1
tag, alert id element, on which is mouseover now, how make this?
<div id="div_1" style="width: 100px; height: 100px; background-color: #090"></div>
<div id="div_2" style="width: 100px; height: 100px; background-color: #900"></div>
Upvotes: 0
Views: 261
Reputation: 23580
Is this what you want?
HTML
<div id="container">
<div id="1">1</div>
<div id="2">2</div>
</div>
JavaScript
$('#container > div').mouseover( function() {
alert ($(this).attr('id'));
});
Demo
EDIT
When not using a parent element for selecting the childs. Simply use a wildcard, like this:
JavaScript
$("[id^=div]").mouseover (function() {
alert ($(this).attr('id'));
});
HTML
<div id="div_1">1</div>
<div id="div_2">2</div>
<div id="div_3">3</div>
DEMO
Upvotes: 2
Reputation: 1074208
Update
In the comments, you say
I need id other element, on which is mouse over now
That's a different question. To do that, you'll want a combination of knowing the mouse has left the div
, and knowing it's entered something else. I'd probably use a combination of mouseleave
and mouseover
for that, like this:
$("#div_1").mouseleave(function() {
// We're leaving the div, set up to capture mouseover
$("....selector for a container of these elements...").one("mouseover", function(e) {
// Get the ID of the bottommost element
console.log(e.target.id);
// Or alternately, in case it doesn't have one
var elementWithID = $(e.target).closest('[id]');
if (elementWithID[0]) {
console.log(elementWithID[0].id);
}
});
});
But I'd try really, really hard to come up with a different way to deliver the underlying requirement.
Original answer:
The short version:
$("#div_1").mouseout(function() {
alert(this.id); // But I'd avoid alert if I were you, perhaps console.log?
});
But read on...
The long version:
When you set up an event handler with jQuery, when the handler is called, this
is a reference to the DOM element you hooked the event on, and of course id
is the reflected property for the id
attribute.
But remember that mouseout
bubbles, so you'll receive the mouseout
event any time the mouse leaves an element that's within your div
(any of its descendants), even if it didn't leave the div
itself. If you just want to know when it leaves the div
but not any of its descendant elements, use mouseleave
instead (originally IE-only, but jQuery provides it cross-browser).
If you wanted to generalize that to, say, all divs with class foo
:
$("div.foo").mouseout(function() { // Or, of course, mouseleav
console.log(this.id);
});
Upvotes: 2