2

tried to find a way to change a main image when hovering over an LI

Looking at Using only CSS, show div on hover over <a> I thought I could make it work, but when I moved the div it of course no longer worked.

Here is how I would do it with JavaScript - can you show me how to do the same with pure CSS on the same html?

<html>
<head>
<script>
var myImages = {li1:"image1.jpg",li2:"image2.jpg",li3:"image3.jpg"};
window.onload=function() {
  var lis = document.getElementById('myList').getElementsByTagName('li');
  for (var i=0;i<lis.length;i++) {
    lis[i].onmouseover=function() {
       document.getElementById('image1').src=myImages[this.id];
    }
  }
}
</script>
</head>
<body>
<img id="image1" />
<ul id="myList">
<li id="li1">show image1</li>
<li id="li2">show image2</li>
<li id="li3">show image3</li>
</ul>
</body>
</html>
Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 2
    The only way you're going to get this done in pure CSS is to nest the images inside the li elements and use absolute positioning to put the images where you want them. Then show and hide the image based on the :hover state of each li. This make sense? – S16 May 15 '12 at 17:45
  • Very much. Thanks - could you think of an example with as little hardcoding of image positions or such as possible? Or maybe a sprite (probably too large a file though)? – mplungjan May 15 '12 at 20:43

1 Answers1

4

As requested in your comment:

http://jsfiddle.net/wjBjZ/

This is a basic example showing the list and the image(s) behaving as you requested. Play with the positioning for fine tuning.

Implementing your comment

http://jsfiddle.net/QgJTN/2/

#main {
    position: absolute;
    top: 0px;
    left: 10px;
    border: solid 5px red;
}
#myList{
    background: #ccc;
    position: absolute;
    top:110px;
}
#myList span{
    cursor: pointer;
}
#myList img{
    display: none;
    width: 100px;
    height: 100px;
    position: absolute;
    top: -110px;
    left: 10px;
    border: solid 5px red;
}
#myList li:hover{
    background: #888;
}
#myList li:hover img{
    display:block;
}

HTML

<img id="main" src="http://lorempixel.com/100/100/abstract/" />
<ul id="myList">
    <li>
        <span>List Item One</span>
        <img src="http://lorempixel.com/100/100/abstract/" />
    </li>
    <li>
        <span>List Item Two</span>
        <img src="http://lorempixel.com/100/100/fashion/" />
    </li>
    <li><span>List Item Three</span>
        <img src="http://lorempixel.com/100/100/city/" />
    </li>
</ul>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
S16
  • 2,963
  • 9
  • 40
  • 64
  • That is very cool. Can we have a default image above the list and change that image (overlay) - this does not work:http://jsfiddle.net/mplungjan/QgJTN/ - I already gave you +1 for the lorempixel. That is gold! – mplungjan May 16 '12 at 06:23