mwbarry Posted September 6, 2011 Share Posted September 6, 2011 I am trying to create a homepage in which when the user hovers over an item on the nav bar, a corresponding image appears and then stays on the page until the user hovers over a different nav bar item. Is there a way to link the hovering over the nav bar item to the appearance of the corresponding image in the same way 'this' is used? I am basically trying to streamline the following script to say 'display the corresponding image as block until something else is hovered over' without having to list each items display state.jquery <script type="text/javascript"> $(menu); function menu() { $("#about").hover( function() { $("#img2").css({display:"none"});$("#img3").css({display:"none"});$("#img1").css({display:"block"}); }, function() { $("#img1").css({display:"block"}); } ) $("#food").hover( function() { $("#img1").css({display:"none"});$("#img3").css({display:"none"});$("#img2").css({display:"block"}); }, function() { $("#img2").css({display:"block"}); } ) $("#contact").hover( function() { $("#img1").css({display:"none"});$("#img2").css({display:"none"});$("#img3").css({display:"block"}); }, function() { $("#img3").css({display:"block"}); } ) }</script> html <div id="content"> <div id="images"> <div id="img1"> <img src="images/1.jpg" alt="1" width="440px" /> </div> <div id="img2"> <img src="images/2.jpg" alt="2" width="440px" /> </div> <div id="img3"> <img src="images/3.jpg" alt="3" width="440px" /> </div> </div> <div id="nav"> <a href="#" class="nav" id="about">About</a> <br /> <a href="#" class="nav" id="food">Food</a> <br /> <a href="#" class="nav" id="contact">Contact</a> </div></div> Link to comment Share on other sites More sharing options...
thescientist Posted September 6, 2011 Share Posted September 6, 2011 I would probably create a mapping to associate a menu item with another element and just us a simple loop for handling the showing hiding. $(document).ready(function(){ var map = { 'about' : $('#img1'), 'food' : $('#img2'), 'contact : $('#img3) }; $('.nav').hover(function(){ var id = this.id; foreach(var m in map){ var image = map[m]; if(m === id){ image.show(); }else{ image.hide(); }; };}; Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.