i have the following jquery code.
basically i will have several overlapped divs and a list of links on the right of all those overlapped divs. when hovering over a link, the link’s assigned div will fade in.
I have the following code and it works (it uses the default windows’ sample pictures), but if someone can think of a way to optimize it or make it generic, i’d appreciate it.
<html> <head> <script type='text/javascript' src='jquery-1.2.6.min.js'></script> <script type='text/javascript'> $(document).ready(function() { $('#trigger1').mouseover(function() { $('.contentdiv').addClass('inactive'); $('#divsunset').removeClass('inactive'); $('.inactive').fadeOut(500); $('#divsunset').fadeIn(500); }); $('#trigger2').mouseover(function() { $('.contentdiv').addClass('inactive'); $('#divwinter').removeClass('inactive'); $('.inactive').fadeOut(500); $('#divwinter').fadeIn(500); }); $('#trigger3').mouseover(function() { $('.contentdiv').addClass('inactive'); $('#divbh').removeClass('inactive'); $('.inactive').fadeOut(500); $('#divbh').fadeIn(500); }); $('#trigger4').mouseover(function() { $('.contentdiv').addClass('inactive'); $('#divwl').removeClass('inactive'); $('.inactive').fadeOut(500); $('#divwl').fadeIn(500); }); }); </script> <style> #divsunset { position: absolute; top: 5px; left: 5px; } #divwinter { position: absolute; top: 5px; left: 5px; } #divbh { position: absolute; top: 5px; left: 5px; } #divwl { position: absolute; top: 5px; left: 5px; } #links { position: absolute; top: 800px; left: 700px; } .inactive { } </style> </head> <body> <div id='divsunset' class='contentdiv'> <img src='Sunset.jpg' /> </div> <div id='divwinter' class='contentdiv'> <img src='Winter.jpg' /> </div> <div id='divbh' class='contentdiv'> <img src='bh.jpg' /> </div> <div id='divwl' class='contentdiv'> <img src='wl.jpg' /> </div> <br /> <div id='links'> <a href='#' id='trigger1'>Show Sunset</a> <a href='#' id='trigger2'>Show Winter</a> <a href='#' id='trigger3'>Show Blue Hills</a> <a href='#' id='trigger4'>Show Waterlillies</a> </div> </body> </html>
Thank you Matt, TM and kRON, your responses really helped.
I dont feel I explained myself totally, but TM provided the answer I was looking for.
I wanted to follow DRY and the code TM provided helped me best this time since it did not require for me to alter my markup, just the jQuery code.
Again, thanks a lot. Its amazing how quickly I got the answer. Keep up the great work.
The first thing you can do, to make it cleaner is replace all those similar calls with something more generic.
(note: assume all of this is inside of
document.ready())Using comma-delimited selectors is a great way to obey DRY with jQuery.
I use
$(element).data()to set and retrieve a some data on the element, in this case, the selector used to update the appropriate element.Also, just for a cleaner visual look, you can use the following in the place of
$(document).ready(), if you prefer it. It’s the exact same thing, just a different syntax.