Change text in element when another element is hovered over

Issue

I have three button elements and depending on which button is hovered over I want the text box
to have a diffrent text. When not hovering over the buttons text element should have "See details here". I would like to have 20 buttons is there a better solution than the one below?

var button1 = document.querySelector(".button1");
var button2 = document.querySelector(".button2");
var button3 = document.querySelector(".button3");

var textBox = document.querySelector(".text-box")

button1.addEventListener("mouseover", button1function, false);
button2.addEventListener("mouseover", button2function, false);
button3.addEventListener("mouseover", button3function, false);
button1.addEventListener("mouseout", func1, false);
button2.addEventListener("mouseout", func1, false);
button3.addEventListener("mouseout", func1, false);

function button1function()
{
   textBox.innerHTML = "Hovering over button 1"
}

function func1()
{  
    textBox.innerHTML = "See details here"
}

function button2function()
{
   textBox.innerHTML = "Hovering over button 2"
}

function button3function()
{
   textBox.innerHTML = "Hovering over button 3"
}
.text-box {
    width: 400px;
    height: 100px;
    border: 1px solid blue;
}
    <div class="button-box">
        <button class="button1">Button 1</button>
        <button class="button2">Button 2</button>
        <button class="button3">Button 3</button>
    </div>
    
    <p class="text-box">See details here</p>

Solution

Use an object to hold all the messages, and give the elements a data attribute containing the key in the object.

Give all the elements a common class so you can select them and loop over them.

const textBox = document.querySelector(".text-box")

const messages = {
  b1: "Hovering over button 1",
  b2: "Hovering over button 2",
  b3: "Hovering over button 3"
};

document.querySelectorAll('button.msg').forEach(button => {
  button.addEventListener("mouseover", e => textBox.innerHTML = messages[e.currentTarget.dataset.msg], false);
  button.addEventListener("mouseout", func1, false);
});

function func1() {
  textBox.innerHTML = "See details here"
}
.text-box {
  width: 400px;
  height: 100px;
  border: 1px solid blue;
}
<div class="button-box">
  <button class="button1 msg" data-msg="b1">Button 1</button>
  <button class="button2 msg" data-msg="b2">Button 2</button>
  <button class="button3 msg" data-msg="b3">Button 3</button>
</div>

<p class="text-box">See details here</p>

Answered By – Barmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published