Search code examples
jqueryrollover

Quick and easy jquery li/div change


just wondering if someone can help me make this code work properly and be used for multipul li's without declaring each one separately. Is this possible? Basically want to do an background image rollover with the < li > then when hovering over the < li > have a the contents of #show change. Does that make sense? Any clues of help would be much appreciated.

Code so far:

JQUERY:

function switchTo(i) {
  $('#menu li').css({background:"url(images/1.png) no-repeat top left"}).eq(i).css({background:"url(images/1.png) no-repeat bottom left"});
  $('#show div').css('display','none').eq(i).css('display','block');
  $('#menu li').css({background:"url(images/2.png) no-repeat top left"}).eq(i).css({background:"url(images/2.png) no-repeat bottom left"});
  $('#show div').css('display','none').eq(i).css('display','block');
  $('#menu li').css({background:"url(images/3.png) no-repeat top left"}).eq(i).css({background:"url(images/3.png) no-repeat bottom left"});
  $('#show div').css('display','none').eq(i).css('display','block');
  $('#menu li').css({background:"url(images/4.png) no-repeat top left"}).eq(i).css({background:"url(images/4.png) no-repeat bottom left"});
  $('#show div').css('display','none').eq(i).css('display','block');
}
$(document).ready(function(){
  $('#menu li').mouseover(function(event){
    switchTo($('#menu li').index(event.target));
  });
  switchTo(0);
});

HTML:

<ul id="menu">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<div id="show">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

Thanks again.


Solution

  • It looks like your simply trying to mimic the :hover class of CSS:

    #menu li.one:hover {
        background: url(images/1.png) no-repeat top left;
    }
    
    /* etc. */
    

    As for the showing the content with the matching div bit, by altering your HTML a bit:

    <ul id="menu">
      <li class="one"><div>1</div></li>
      <li class="two"><div>2</div></li>
      <li class="three"><div>3</div></li>
      <li class="four"><div>4</div></li>
    </ul>
    

    And adding some more CSS:

    #menu li div {
       display: none;
    }    
    
    #menu li:hover div {
       display: block;
    }
    

    Working example here