• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 765
  • Last Modified:

jQuery: Select element but NOT child elements

Using jQuery, how can I trigger an event when a user hovers over an element but NOT over one of the element's child elements?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
 $('#selection').hover(function() { alert('You are hovering over the red area NOT the blue area.') }, function() {});
});
</script>

<style type="text/css">

#selection {
height: 500px;
width: 790px;
overflow: hidden;
position: relative;
padding: 0; 
margin: 0 auto;
background: red;
}

#selection p {
background: blue;
height: 500px;
overflow: hidden;
padding: 0; 
margin: 0 auto 0 auto;
width: 300px;
}

</style>

</head>
<body>

<div id="selection">
 <p>
 </p>
</div>

</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
  • 2
1 Solution
 
David S.Commented:
hover() is a shortcut for mouseenter() and mouseleave(), but you want the behavior of mouseover(), not mouseenter(). Check out the demo on this page: http://api.jquery.com/mouseover/#example-0
0
 
hankknightAuthor Commented:
Thanks but I think you missed the point of my question.  I want to know how to select an element without also selecting its children.  I used hover() as an example.  

$('#selection<BUT_NO_CHILDREN').hover(.....

Open in new window

0
 
David S.Commented:
You can't do that with selectors. You have to trap the event on the descendants so it doesn't bubble up to the parent.

$(document).ready(function() {
  $('#selection').mouseover(function() { alert('You are hovering over the red area NOT the blue area.') });
  $('#selection').find('*').mouseover(function(e) { e.stopPropagation(); return false; });
});

Open in new window

P.S. Is there a particular reason why you're using that old version of jQuery? The current version is 1.6.4.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now