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.
JavaScript
x
20
20
1
<div id="content">
2
Stuff should be placed here.
3
</div>
4
5
<br/>
6
<br/>
7
<br/>
8
<ul>
9
<li onmouseover="hover('Apples are delicious')">Apple</li>
10
<li onmouseover="hover('oranges are healthy')">Orange</li>
11
<li onmouseover="hover('Candy is the best')">Candy</li>
12
</ul>
13
14
<script>
15
function hover(description) {
16
console.log(description);
17
document.getElementById('content').innerHTML = description;
18
}
19
</script>
20
Advertisement
Answer
You need to store the original text and bring it back when the mouse leaves.
JavaScript
1
12
12
1
var element = getElementById('content'),
2
storedText;
3
4
function hover(description) {
5
console.log(description);
6
storedText = element.innerHTML;
7
element.innerHTML = description;
8
}
9
10
function leave() {
11
element.innerHTML = storedText;
12
}
JavaScript
1
12
12
1
<div id="content">
2
Stuff should be placed here.
3
</div>
4
5
<br/>
6
<br/>
7
<br/>
8
<ul>
9
<li onmouseover="hover('Apples are delicious')" onmouseleave="leave()">Apple</li>
10
<li onmouseover="hover('oranges are healthy')" onmouseleave="leave()">Orange</li>
11
<li onmouseover="hover('Candy is the best')" onmouseleave="leave()">Candy</li>
12
</ul>
It is generally recommended to add event listeners in the JS code and not in the HTML, but put that aside for now.