What is the best way to alter the text of a button when the mouse hovers over it?

I'm looking to create a button that can dynamically change the text inside it when the cursor hovers over it, and then revert back to the original text when the cursor moves away from it. I attempted this in VScode using "document.getElementById().innerHTML", but encountered an issue where the text did not revert to its original state.

button  {
    
    background-color: green;
    border-color: white;
    border-radius: 10px;
    align-self: center;
}
body  {
    background-color: black;
}

h1  {
    color:green;
    text-align: center;
}

p   {
    color: chartreuse;
    font-family: Verdana;
    font-size: 12px;
}
button:hover{
    background: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="website.css">

</head>
<body>
<h1>Web Page</h1>

<!-- Buttons -->
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click to display Date and Time</button>
<p id="demo"></p>

<button type="button"
onmouseover="this.innerHTML = Date()"
onmouseout="document.getElementById">What time is it</button>
<script>
    var x = "What time is it";
    document.getElementById("time").innerHTML = x;
</script>

Answer №1

If you want to update the content of a button using JavaScript based on mouse entry and exit events, you can use the `mouseenter` and `mouseleave` events along with changing the innerHTML property of the button element.

const btnElement = document.getElementById("button1");
btnElement.addEventListener('mouseenter', event => {
  btnElement.innerHTML = "Click Me";
});

btnElement.addEventListener('mouseleave', event => {
    btnElement.innerHTML = "Hover Over Me";
});
<!DOCTYPE html>
<html>
    <head>
        <title>
              
        </title>
    </head>
      
    <body>
        <div>
            <button id="button1">Hover Over Me</button>
        </div>
    </body>
</html>

Answer №2

One way to approach this is by using two <span> elements within the button. The first <span> would display the default text, while the second <span> would contain the text shown on hover, initially hidden.

To implement this, you can add an event listener to the button. Upon mouseover, hide the default text and display the span with the hover text. On a mouseleave event, revert the display back to the default settings.

Here's an example of the HTML structure:

<button id="mybutton">
  <span class="default-text">Default Text</span>
  <span class="hover-text" style="display: none;">Hover Text</span>
</button>

And the corresponding JavaScript code:

var btn = document.getElementById('mybutton');

btn.addEventListener('mouseover', function() {
    this.querySelector('.hover-text').style.display = 'block';
    this.querySelector('.default-text').style.display = 'none';
});

btn.addEventListener('mouseleave', function() {
    this.querySelector('.default-text').style.display = 'block';
    this.querySelector('.hover-text').style.display = 'none';
});

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

Running npm commands from the root directory while the package.json file is located elsewhere

Although I understand that it's not ideal, I am faced with a specific directory structure that cannot be changed: [projectRootDir] [src] [tests] [otherDirs] [configuration] package.json mocha.opts other files.. ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...

How can I line up two divs horizontally within a container div?

Apologies if my terminology is off, I am relatively new to this. My goal is to align two divs horizontally, one containing an image and the other the message content. I have created a messaging user interface. Everything was functioning correctly until I ...

Issues encountered with PHP integration for Bootstrap carousel

I'm facing a challenge with modifying an existing carousel to load data from an SQL database instead of hardcoding it. After successfully fetching the data using PHP, I noticed that the controls of the carousel are not functioning as expected. Upon i ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

Submitting a form from outside the form using a button in HTML: A step-by-step guide

I'm looking to submit a form using Angular on the functions next() and saveStep(). I'm unable to place next() and saveStep() within the form itself. I have set up my ng-click for next() and saveStep() below the form. When I submit the form fro ...

How can we programmatically trigger a click action on an element obtained through an HTTP request with the help of Set

window.addEventListener("load" , () => { setInterval(() => { let xhttp = new XMLHttpRequest(); xhttp.open("GET", "./messagedUsers.php", true); xhttp.onload = () => { if(xhttp.re ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

The component 'AddPlaceModal' could not be located in the path '~/components/AddPlaceModal.vue'

Recently, I started incorporating Nuxt for Vue into my projects. In an attempt to enhance my page, I added a new component within the /components folder. However, I encountered a warning during compilation: "export 'AddPlaceModal' was not found ...

Is it necessary to use Hapi.js on the client side in order to establish a websocket connection using the Hapi.js protocol?

Currently, I am in the process of developing an API using Hapi and requiring WebSocket functionality. After some research, it appears that Nes is the preferred choice to integrate with Hapi for this purpose. Fortunately, Nes simplifies the process signific ...

Adjust the background of the input range style prior to the thumb icon

Is there a way to style the bar before the thumb with a different color on a range input? I have been searching for a solution without much success. This is the desired look: Unfortunately, Chrome no longer supports input[type='range']::-webkit- ...

Issue with retrieving JSON data through HTTP Get request on Internet Explorer, while it works fine on

Trying to upgrade a basic weather plugin by integrating geolocation services that identify a user's location based on their IP address. Smooth sailing on Chrome and Firefox, but IE seems to be causing some trouble. Any idea what might be the issue wit ...

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

What is causing the input boxes to exceed their container boundaries so drastically?

My plan was to organize 4 input text boxes in 4 equal columns on a single row of the form. Using Bootstrap's grid column classes, I set col--3 for medium and large screens for those four inputs. For small and extra-small sizes, I designated them as co ...

Combining JSON objects within an array

I'm working with a JSON Array that looks like this: [ {"Name" : "Arrow", "Year" : "2001" }, {"Name" : "Arrow", "Type" : "Action-Drama" }, { "Name" : "GOT", "Type" : "Action-Drama" } ] and I want to convert it to look like this: [ { "Name" : ...

Unable to set custom claims using Firebase Auth's setCustomClaims() method

I am encountering an issue with setting custom claims for Firebase Authentication service's token. I am using a Cloud function to establish the custom claims for Hasura. The cloud function is triggered upon the creation of a new user to set the custom ...

What are some ways to reuse an angular component multiple times?

I am utilizing an angular component to dynamically load charts into my widget: Below is an example of the component: angular.module("generalApp").component("chartPie", { template: "<div class=Pie></div>", bindings: { data: "=", }, control ...

Struggling to calculate the total of a property within an array of objects

I'm currently trying to calculate the sum of a specific property within an array object. Although I successfully accomplished this in one component, I am encountering difficulties replicating it in another. The error message being displayed is: this. ...

What is the best way to engage in conversations with several users using socket.io?

Currently, I am in the process of developing a chat application with authentication. The implementation involves socketio for real-time communication and jwt along with cookies for user authentication. The connection to the database has been successfully e ...

Experiencing difficulty incorporating JSON and JS into jQueryhandleRequestJSON and JS integration with jQuery

I'm having trouble fetching the 'sigla' field from a JSON file and inserting it into an HTML 'option object'. I could use some assistance with this issue, so if anyone out there can lend a hand, it would be much appreciated! Here ...