How do you swap DIVs on mouseover (jQuery)?

Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the “active” class pre-set on the proper switch/slide.

$(document).ready(function() {
  switches = $('#switches > li');
  slides = $('#slides > div');
  switches.each(function(idx) {
    $(this).data('slide', slides.eq(idx));
  }).hover(
    function() {
      switches.removeClass('active');
      slides.removeClass('active');
      $(this).addClass('active');
      $(this).data('slide').addClass('active');
    });
});
#switches .active {
  font-weight: bold;
}
#slides div {
  display: none;
}
#slides div.active {
  display: block;
}
<html>

<head>

  <title>test</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script type="text/javascript" src="switch.js"></script>

</head>

<body>

  <ul id="switches">
    <li class="active">First slide</li>
    <li>Second slide</li>
    <li>Third slide</li>
    <li>Fourth slide</li>
  </ul>
  <div id="slides">
    <div class="active">Well well.</div>
    <div>Oh no!</div>
    <div>You again?</div>
    <div>I'm gone!</div>
  </div>

</body>

</html>

Leave a Comment