user27370 user27370 - 2 months ago 9
Javascript Question

How to make an image in a separate div change on hover of nav?

I have a site I'm working on where I have a nav bar in a div at the top of the page followed by a separate div which contains an image directly below it.

I'm trying to figure out the best way to change the image by hovering over each part of the nav bar.

Basically I want an image for home to show up when the home nav feature is hovered and so on with the rest of the menu.

UPDATE:

As I tried to explain before (not as clear as I could have) I want to make each nav bar element (Home, Downloads, etc.) show a different image in the div below it. Here is the section of code for the two elements.

<li class="active"><a href="/">Home</a></li>
<li ><a href="/about">About</a></li>
<li ><a href="/mods">Mods</a></li>
<li><a href="/forums">Forums</a></li>
<li ><a href="/downloads">Downloads</a></li>
<li><a href="//blog.blog.com">Blog</a></li>
</ul>
</div>
</nav>

<div class="parallax-container">
<div class="container" style="background: rgb(55,71,79); width:960px; padding-top: 10px; padding-left: 50px; border: 2px; border-radius: 50px;">
<div class="row">
<div class="hover-image white-text col s12 l6">
<img src="homeimage.png" class="hover image" style="height:auto; width:auto; max-width: 860px; max-height: 860px;"/>
<h5 class="hover-header" style="padding-left: 20px;">Home</h2>
<p class="hover-paragraph" style="padding-left: 25px;">Welcome to the page!</p>
</div>
</div>
</div>
<div class="parallax"><img src="/img/image.png"></div>

</div>

<style>
.hover-image {
position: relative;
width: 100%;
margin: auto;
}

.hover-header {
position: absolute;
top: 350px;
left: 10;
width: 100%;
}
.hover-paragraph {
position: absolute;
top: 380px;
width: 100%;
}
</style>


Page Layout

Answer

try this code -

CSS -

#navImage img{
        display:block;
        width:500px;
        height:auto;
     }
     #myNav{
       list-style-type: none;
     }
#myNav li {
    display: inline;
    padding: 10px;
}
#myNav li a:hover {
    color:#00ffff;
}

#navImage img{
    display:none;
}

HTML

<ul id="myNav">
      <li><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>

    <div id="navImage">
      <img src="img_chania.jpg"  alt="Chania">
      <img src="img_chania2.jpg" alt="Chania">
      <img src="img_flower.jpg" alt="Flower">
      <img src="img_flower2.jpg" alt="Flower">
    </div>

JS to initialize (with jQuery) -

  $("#myNav li a").on('mouseover', function(){
        $("#navImage img").hide().eq($(this).closest('li').index()).show();
    });

Please note, if you are working on responsive design(using bootstrap navigation), you need to do changes accordingly.

jsfiddle - https://jsfiddle.net/guruling/k2zgot5r/

Comments