"What is the best way to use JavaScript to dynamically modify the hover color of a button

I am looking to customize the hover color of all buttons on my website to align with the overall theme. The challenge is that I need the hover color to vary based on the page it originates from. I have successfully identified the referring page, but I am struggling to implement the hover style change. Here is the code snippet I currently have:

var btn = {
            hover: function (event) {
                event.target.style.backgroundColor = "blue";
            },
            out: function (event) {
                event.target.style.backgroundColor = "white";
            }

        }

var element = document.getElementsByTagName('button');
        element.addEventListener("mouseover", btn.hover, false);
        element.addEventListener("mouseout", btn.out, false);

HTML:
<div>
   <button class="accountButton firstButton" id="FacebookExchange"></button>
</div>

Default Style:
    .unified_container .row .panel-default #api .localAccount .entry .buttons button {
        float: left;
        background-image: none;
        background-color: #f4f4f4;
        border-radius: 0.2rem;
        cursor: pointer;
        display: inline-block;
        font-size: 1em;
        font-weight: 400;
        height: inherit;
        line-height: 1.3333333;
        margin-top: 3rem;
        margin-right: 0px;
        margin-left: 0px;
        padding: 10px 16px;
        text-align: center;
        touch-action: manipulation;
        user-select: none;
        vertical-align: middle;
        white-space: nowrap;
        width: inherit;
        -moz-user-select: none;
        -ms-touch-action: manipulation;
        -ms-user-select: none;
        -webkit-user-select: none;
        color: #000;
        width: 100%;
    }
        .unified_container .row .panel-default #api .localAccount .entry .buttons button:hover {
            -moz-box-shadow: none;
            -webkit-box-shadow: none;
            box-shadow: none;
            background-color: #d40000;
            color: #fff;
        }

An error message I encounter is "element.addEventListener is not a function".

How can I update the hover color of the buttons effectively?

Note: I cannot insert inline CSS, JavaScript, or HTML within the buttons as they are dynamically generated by the application.

Answer №1

The main issue leading to the error you're encountering is related to the fact that

document.getElementsByTagName('button')
generates an array of elements with the tag name button. As a result, your variable element ends up being an array. To resolve this issue, you will need to pinpoint which specific element in the array you intend to attach a listener to. For instance, if it's the first element, your code should resemble the following:

element[0].addEventListener("mouseover", btn.hover, false);
element[0].addEventListener("mouseout", btn.out, false);

If you desire all your button elements to possess these listeners, you can achieve this by employing a straightforward foreach loop or map.

Answer №2

When using the code

document.getElementsByTagName('button')
, you will receive an array of Nodes. To ensure proper functionality, iterate through the list and attach event listeners to each one.

var buttons = document.getElementsByTagName('button');
buttons.forEach(button => {
    button.addEventListener("mouseover", btn.hover, false);
    button.addEventListener("mouseout", btn.out, false);
});

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

Spicing up javascript with Currie's arrow function

Can you please break down this function in a straightforward way (without using arrows)? I'm having trouble understanding if "foo" in Promise.resolve "foo" is an argument or a callback function. module.exports = function foo(req, res, next) { retu ...

Event triggered only upon initial click

I am experiencing an issue with my category list. When I click on a category to trigger an AJAX request for the first time, the request does not go through. However, when I click on the same category a second time, it works perfectly. Below is the code sni ...

Disabling animations in Reactjs with CSSTransition and Group Transition

Currently, I am experimenting with REACTJS to build a basic app featuring Transitions. In my project file, I have imported CSSTransitions and Group Transition. However, when attempting to implement CSSTransition for specific news items, the animations are ...

Tips on saving an array as a variable

Can anyone help me figure out how to store a PHP variable into a JavaScript variable? var myArray; function retrieveData(id) { $.post( "main/updater.php", { id:id } ).done(function( data ) { myArray = data; }); } I&ap ...

What is the recommended element for managing data in React?

Let's consider a scenario where we have 2 main components: class App extends React.Component { state = { comments: [1, 2, 3, 4] } render() { return ( <Comments /> ) } } class Comments extends React.Component { rende ...

Zurb Foundation gem causing navigation errors

Typically, I rely on the Twitter Bootstrap Rails gem for my projects, but this time I decided to try out the Zurb Foundation gem. Following the installation instructions meticulously, I added the navigation code: <div class="row"> <div class="th ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Splitting a square into four triangles using CSS styling

My current challenge involves creating a square comprised of 4 triangles of equal size, each with hover events. Here is the CSS I'm using to create the triangles: .right, left, .top, .bottom { position: relative; width: 26px; } .right:before ...

When combining Puppeteer with Electron, an error stating "Browser revision not found" may occur. However, this issue does not arise when running with Node

My attempts to make Puppeteer work in Electron have been with various versions of Puppeteer (v5.4.0, v5.4.1, and v5.5.0), on Windows 10/MacOS, and with different Node versions (v12, v14.0.1, v15.0.3). Trying a simple puppeteer.launch() in the main process ...

Guide on how to call a function in ascx code-behind using JavaScript within the framework of DotNetN

Currently, I am facing an issue with my module that involves submitting data to a SQL table in a database using code behind. My validation is done through javascript, and when a button is clicked and the data is valid, a div is displayed. However, the pr ...

Tips on eliminating the top margin on my webpage

I am in need of assistance with removing the margin at the top of my page. Take a look at the screenshot for reference: As shown in the image, there is a red arrow pointing to the problematic margin. Can someone guide me on how to eliminate this margin? B ...

The Dysfunction of JQuery UI 1.12.1 Autocomplete

I am encountering some challenges with implementing JQuery UI. The version of JQuery UI I am using is 1.12.1, the latest one available. I have downloaded the autocomplete feature along with all other necessary widgets. In my project, I have placed jquery ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Unit Testing JWT in Angular 2

Using JWT for authentication in my API calls. I am in the process of coding a service method. An interceptor is applied to all requests: public interceptBefore(request: InterceptedRequest): InterceptedRequest { // Modify or obtain information from ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Passing data from client to express.js using Javascript

I'm having trouble sending a variable from a JavaScript application to a Node.js server. Here's the code snippet: //client side $.get('http://smart-shopper.ro/messages?from=lastGeneralTimeStamp', datas => { console.log("dat ...

Cookie Consent has an impact on the performance of PageSpeed Insights

On my website, I have implemented Cookie Consent by Insights. The documentation for this can be found at However, I noticed a significant drop in my Google PageSpeed Insight scores after loading the JavaScript source for Cookie Consent. The main issue hig ...

In ReactJS, one can create a variable and include a map function by first declaring the variable and then using the map function within the component. If you

Having trouble integrating the accordian.js page into the app.js main page for compilation. Need help defining and writing out the function correctly, any suggestions? Below is my code: App.js: How do I incorporate the components from the accordian.js pa ...

Why does my ajax request show the result in the php file rather than redirecting to the html page?

I've developed a series of AJAX functions that retrieve data from a PHP file. However, one of the functions redirects to the PHP file to fetch data but fails to return to the HTML page for data insertion. Here is the code used to fetch a table from a ...

How can I show pagination links as buttons on a gridview in ASP.NET?

When working on asp.net web forms, I encountered an issue where I was unable to display pagination links as buttons with a gray background on the grid view control. To achieve this, I needed to assign a CSS class to the pager style on the grid view in ord ...