JQuery – Hover And Show Next Element
So, this JQuery code shows the next element (a DIV in this case) when you hover over a “trigger” (in this case, the triggers are hyperlinks), and then hides the element (the DIV and its contents) once you hover out. Below is a demo of exactly what I mean…
Here’s the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function() {
$(".demo_containers .sub a").hover(function() {
$(this).next("div").show("slow");
},function(){
$(this).next("div").hide("slow");
});
});
</script>
<style type="text/css">
.demo_containers .sub div{
display:none;
}
</style>
</head>
<body>
<div class="demo_containers">
<div class="sub">
<a href="#">Demo Link- Gallery</a>
<div class="desc">
Take a look at some of our projects, ranging from CSS to eCommerce websites.
</div>
</div>
<div class="sub">
<a href="#">Demo Link- About Us</a>
<div>
Read more about BrightCherry- what we do, how we do it and how we started.
</div>
</div>
</div>
</body>
</html> |
That’s a very basic example.
Using the parent() function
This feature can get more complicated if the trigger (the hyperlink) is wrapped in an extra element. For example, if the code looked like this:
1 2 3 4 5 6 7 8 | <div class="sub">
<span>
<a href="#">Demo Link- Gallery</a>
</span>
<div class="desc">
Take a look at some of our projects, ranging from CSS to eCommerce websites.
</div>
</div> |
If you look carefully, the trigger (hyperlink) now has an extra span tag around it. The previous JQuery code will no longer work because the “next” element after the hyperlink (a tag) is no longer the DIV you want to show, it’s the SPAN tag.
1 2 3 4 5 6 7 8 9 | <script type="text/javascript">
$(function() {
$(".demo_containers .sub a").hover(function() {
$(this).parent().next("div").show("slow");
},function(){
$(this).parent().next("div").hide("slow");
});
});
</script> |
In order to get the code to work we need to access the next element after the SPAN, which is why we need the parent() function to select the parent of the hyperlink (which is the SPAN tag), and then select the “next” DIV element after the SPAN.
I’m probably not explaining it very well, but the example code should explain it better than I do



brightcherry.co.uk
Leave a Reply