Modify the content of an element upon hovering over a different element

I have a set of three buttons and I want the text displayed in a box to change based on which button is being hovered over. If no button is being hovered, the default text should be "See details here". Is there a more efficient way to achieve this functionality with multiple buttons?

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>

Answer №1

Utilize an object to store all the messages, and assign a data attribute to each element with the corresponding key in the object.

Add a shared class to all elements for easy selection and looping through 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>

Answer №2

Implement the mouseover event on the container that holds all the buttons. This allows you to handle multiple buttons within that container (.button-box) with just one event listener. By utilizing event delegation, you can even traverse up the DOM tree all the way to

window</code) efficiently. Check out more about <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation" rel="nofollow noreferrer">event delegation</a></p>
<p><div>
<div>
<pre class="lang-js"><code>document.querySelector('.button-box').onmouseover = messageID;

function messageID(event) {
  const hvr = event.target;
  document.querySelector('.text-box').textContent = hvr.className;
}
.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>
  <button class="button11">Button 11</button>
  <button class="button12">Button 12</button>
  <button class="button13">Button 13</button>
  <button class="button21">Button 21</button>
  <button class="button22">Button 22</button>
  <button class="button23">Button 23</button>
  <button class="button31">Button 31</button>
  <button class="button32">Button 32</button>
  <button class="button33">Button 33</button>
  <button class="button41">Button 41</button>
  <button class="button42">Button 42</button>
  <button class="button43">Button 43</button>
  <button class="button51">Button 51</button>
  <button class="button52">Button 52</button>
  <button class="button53">Button 53</button>
  <button class="button61">Button 61</button>
  <button class="button62">Button 62</button>
  <button class="button63">Button 63</button>
  <button class="button71">Button 71</button>
  <button class="button72">Button 72</button>
  <button class="button73">Button 73</button>
  <button class="button81">Button 81</button>
  <button class="button82">Button 82</button>
  <button class="button83">Button 83</button>
  <button class="button91">Button 91</button>
  <button class="button92">Button 92</button>
  <button class="button93">Button 93</button>
</div>

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

Answer №3

To make things easier, group all buttons under a common class and specify the message you want each button to display within its button tag. Then, utilize querySelectorAll to select all buttons and cycle through the list of elements to attach event listeners. Here's an illustration:

var textBox = document.querySelector(".text-box")
var buttons = document.querySelectorAll('.btn')

buttons.forEach(button => {
  button.addEventListener("mouseover", () => {
    textBox.innerHTML = button.dataset.hover
  }, false);

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

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

Answer №4

It was almost too late...

const links = document.getElementsByClassName("hover-link");
const textBox = document.querySelector(".text-box")

Array.prototype.slice.call(links).forEach(link => link.addEventListener("mouseover", onMouseOver, false));
Array.prototype.slice.call(links).forEach(link => link.addEventListener("mouseout", onMouseOut, false));

function onMouseOver(e)
{
  textBox.innerHTML = e.target.innerText;
}

function onMouseOut()
{  
  textBox.innerHTML = "Details are shown here"
}
.text-box {
    width: 400px;
    height: 100px;
    border: 1px solid blue;
}
    <div class="link-box">
        <a class="hover-link">Link 1</a>
        <a class="hover-link">Link 2</a>
        <a class="hover-link">Link 3</a>
        <a class="hover-link">Link 4</a>
        <a class="hover-link">Link 5</a>
        <a class="hover-link">Link 6</a>
        <a class="hover-link">Link 7</a>
        <a class="hover-link">Link 8</a>
        <a class="hover-link">Link 9</a>
        <a class="hover-link">Link 10</a>
        <a class="hover-link">Link 11</a>
        <a class="hover-link">Link 12</a>
        <a class="hover-link">Link 13</a>
        <a class="hover-link">Link 14</a>
        <a class="hover-link">Link 15</a>
        <a class="hover-link">Link 16</a>
        <a class="hover-link">Link 17</a>
        <a class="hover-link">Link 18</a>
        <a class="hover-link">Link 19</a>
        <a class="hover-link">Link 20</a>
    </div>
    
    <p class="text-box">Details are shown here</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deselect a radio button with a click event using jquery

When the page refreshes, radio buttons are left unchecked. <input type="radio" name="test"> 1<input type="radio" name="test">2 <input type="button" id="btn" /> $("#btn").click(function(){ $(':radio').each(function () { ...

When running collection.find().toArray(callback) in node.js with mongodb, the result is coming back

When I run my code, mydocuments.find({}).toArray is returning empty. I have seen some solutions posted but they don't apply to my situation since I am using MongoClient.connect. Any help would be greatly appreciated. var MONGOHQ_URL="mongodb://harish ...

Tips for deleting an object in a JSON file using a PHP script

I am currently working on a project where I need to dynamically populate an HTML file with data from a JSON file using an ajax POST request. However, I'm facing an issue while trying to extract a specific object from the JSON array based on an index n ...

Message successfully sent despite Ajax failure

Hello everyone, I'm currently facing an issue while trying to send a message using the form craft plugin. The error message that I am encountering is " 504 (Gateway Time-out)" along with some technical details: send @ jquery.js:4 ajax ...

Handler for stack trace errors and error handling for promises

Introducing my customized error handling function: function onError(message, source, lineno, colno, error) { sendRequestToSendMail(arguments) } window.onerror = onError In addition to that, I have asynchronous tasks utilizing promises and I aim to captur ...

Typescript is struggling to locate a module that was specified in the "paths" configuration

Within my React project, I have set up a module alias in the webpack config. Now, I am looking to transition to Typescript. // I have tried to simplify the setup as much as possible Here is my tsconfig.json located in the root directory: { "compilerOp ...

Developing components and injecting them dynamically in Angular 2 using Typescript remotely

I am currently exploring the potential of Angular 2 as a foundational technology for a flexible administration dashboard, emphasizing the need for extensibility and customization. I envision an environment where external developers can create their own c ...

JavaScript data structure similar to ListOrderedMap/ArrayMap

Does anyone know of a JavaScript data structure that functions similarly to ListOrderedMap? I need it to have the capability to add an object at a specific index, retrieve the index for a given object, and lookup an object by its id. Unfortunately, all t ...

My mobile browsing experience is being hindered by a high CLS score due to the image continuously loading late

This is the webpage I am experiencing problems with, and here is the Google Pagespeed report for Mobile. Despite trying to stop lazy loading and preloading the image, there is always a delay in loading. How can this issue be resolved? ...

Calculating the number of days between two given dates, including both the start and end dates

I need to calculate the number of days between two dates, including both of the dates. My current method for this task is as follows: numDaysBetweenDates(startDate, endDate) { let millisecondsPerDay = 24 * 60 * 60 * 1000; return (endDate - startDate) ...

jQuery siblings toggling issue unresolved

I am new to jQuery and I'm trying to create a toggle effect between sibling divs. In other words, when I click to show the next div, the previous one should automatically close. Currently, the previous div doesn't close when the next one is opene ...

Is it possible to have both Node.js and browser code in the same file using webpack, while ensuring that only the browser code is accessible and the Node.js code remains hidden?

I need to work with a file that contains both Node.js and browser code. It's crucial that the Node.js code remains hidden when running in the browser environment. Is it possible for Webpack to exclude specific sections of the code based on the enviro ...

JavaScript array manipulation

I am working with an array of objects that have a year and count property like this: [{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}, ....] My goal is to popu ...

Get an Object Array and assign it to a state Array variable after filtering

Here is a JSON Input that I will be filtering by orderId and then setting to a state variable. [{"orderId":3,"userId":3,"firstName":"Amal","lastName":"kankanige","contactNo":"011-3456787","status":"pending","deliveryAddress":"No:24/c,Anders Road,Wijerama, ...

What are the best ways to change the styling of jquery ui widgets?

Currently utilizing jQuery UI, I have encountered an issue with the font size within a dialog. When utilizing the standard settings, the font size appears to be excessively large. To address this, I used the element inspector to identify the class name o ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

Proper handling of retrieving POST method data on the current page

I'm uncertain if I'm handling my "same page" forms effectively. My current method involves adding a hidden input named "action" with value='1' to the form. Then, at the start of the page, I check if $_POST["action"] has a value, and ...

The data-ls attribute is currently not permitted on the svg element. Is there a way to fix this issue?

Upon running my site through the w3cvalidator tool, I encountered the following errors: "Attribute data-ls not allowed on svg element at this point" and "End tag svg did not match the name of the current open element (use)". Below is a snippet of the cod ...

I am experiencing issues with the jQuery function within my MVC Application

When working on my MVC application, I encountered an issue where the onclick function was not functioning as expected. @section Scripts{ <script src="~/Scripts/plugins/toastr/toastr.min.js"></script> <script> $(document). ...

Opening a navigation app through a smartphone webpage

My goal is to enable users to click on a postcode and open their native map app. Most of the solutions I've come across are tailored to specific vendors. Is there a universal "maps" protocol that can launch the native app? Could something like "maps ...