Skip to content
Advertisement

Change div content on mouse hover with default content fallback

I’ve implemented the accepted answer to Change div content based on mouse hover on different divs across a lot of links, so I don’t really want to go with another solution if it can be avoided. I’m trying to figure out one more piece of the puzzle though…

I can’t seem to get it to where it defaults back to the original text of the content div when not hovering over an item.

<div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')">Apple</li>
    <li onmouseover="hover('oranges are healthy')">Orange</li>
    <li onmouseover="hover('Candy is the best')">Candy</li>
</ul>

<script>
    function hover(description) {
        console.log(description);
        document.getElementById('content').innerHTML = description;
    }
</script>

Advertisement

Answer

You need to store the original text and bring it back when the mouse leaves.

var element = getElementById('content'),
  storedText;

function hover(description) {
    console.log(description);
  storedText = element.innerHTML;
  element.innerHTML = description;
}

function leave() {
    element.innerHTML = storedText;
}
<div id="content">
    Stuff should be placed here.
</div>

<br/>
<br/>
<br/>
<ul>
    <li onmouseover="hover('Apples are delicious')" onmouseleave="leave()">Apple</li>
    <li onmouseover="hover('oranges are healthy')" onmouseleave="leave()">Orange</li>
    <li onmouseover="hover('Candy is the best')" onmouseleave="leave()">Candy</li>
</ul>

It is generally recommended to add event listeners in the JS code and not in the HTML, but put that aside for now.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement