Activate hover effect on toggle button

When I hover over the "CHANGE" button, the orange color appears as expected. Clicking the button once turns the color red but removes the hover color, which is fine. However, clicking it twice brings back the original blue color but the hover effect is missing. Is there a way to have the hover color disappear on the first click and reappear on the second click, just like at the beginning?

var someFunction = {};

function changeColor() {
        var button = document.getElementById('mute1').style.backgroundColor;
        var color = '';
        this.active = !this.active;
        someFunction["one"] = this.active;
        someFunction["two"] = this.active;
        if (button !== 'red') {
            color = 'red';
            document.getElementById('mute1').style.backgroundColor = color;
            document.getElementById('mute1').style.color = "#fff";
        } else if (button === 'red') {
            color = '#2c475c';
            document.getElementById('mute1').style.backgroundColor = color;
            document.getElementById('mute1').style.color = "#fff";
            this.active = !this.active;
            someFunction[this.function] = this.active;
        }
    }
#mute1 {    
  padding: 25px 50px;
    background: #2c475c;
    color: #fff;
  border-radius:5px;
}

#mute1:hover {  
  background: orange;
}
<button id="mute1" onclick="changeColor();">CHANGE</button>

Answer №1

The issue lies in the fact that the hover effect changes color through a class, while the click event modifies the inline style, which takes precedence. Upon inspecting with browser dev tools, you will notice that the element acquires an inline background style after the first click.

If you wish to ensure that the hover always results in an orange background color, you have a few options:

  • Stick to altering the inline style on click but also incorporate an event listener for mouseover using JavaScript to change the background to orange.

  • Utilize classes for all updates.

This code snippet eliminates the hover class and introduces event listeners for mouseenter, mouseout, and click actions on the button.

A global color variable is employed so it can be used in the mouseout event to revert back to the previous color (either red or gray).

The provided code is quite basic and ideally should be transformed into proper JS functions with addEventListeners rather than relying on inline onclick attributes.

let color = '#2c475c';
var someFunction = {};

function hovered() {}

function changeColor() {
  var button = document.getElementById('mute1').style.backgroundColor;
  /*var */
  color = '';
  this.active = !this.active;
  someFunction["one"] = this.active;
  someFunction["two"] = this.active;
  if (button !== 'red') {
    color = 'red';
    document.getElementById('mute1').style.backgroundColor = color;
    document.getElementById('mute1').style.color = "#fff";
  } else if (button === 'red') {
    color = '#2c475c';
    document.getElementById('mute1').style.backgroundColor = color;
    document.getElementById('mute1').style.color = "#fff";
    this.active = !this.active;
    someFunction[this.function] = this.active;
  }
}
#mute1 {
  padding: 25px 50px;
  background-color: #2c475c;
  color: #fff;
  border-radius: 5px;
}
<button id="mute1" onclick="changeColor();" onmouseenter="this.style.backgroundColor = 'orange';" onmouseout="this.style.backgroundColor = color;">CHANGE</button >

Answer №2

Delete the semi-colon from the onclick attribute:

<button id="mute1" onclick="changeColor()">CHANGE</button>

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

Consolidating multiple inputs into a single saved value

How can I combine three input values into one input field using onchange event in JavaScript? <script type="text/javascript"> function updateInput($i){ $('updateval').val($i); } </script> <input type="text" onchange="updat ...

Looking for an xpath to target elements within a neighboring table

I am having trouble creating an xpath expression to find the text located in the span tag that contains text to locate in the second portion of the xpath. The text should be found by first locating an image inside a table row within a table data cell in a ...

Adding a tooltip with a date format to a Highchart graph

Hey everyone, I'm currently working with a Highchart and I want to customize the tooltip value in a specific format. My categories and series are structured as follows: {"Categories":["2015-11-09","2015-11-08""2015-11-15"],"Series":[2,0,2]} Current ...

Tips on displaying information following the parsing of JSON

Trying to retrieve a list of users using this code snippet <div id="users" data-users='[{"name":"one","userName":"user_one"}, {"name":"two","userName":"user_two&q ...

Vue: utilizing shared methods in a JavaScript file

Currently, I am building a multipage website using Vue and I find myself needing the same methods for different views quite often. I came across a suggestion to use a shared .js file to achieve this. It works perfectly when my "test method" downloadModel i ...

I am interested in sending an email from a PDF document based on the selected check boxes

I have added a button in a PDF form that says "send an email" and I would like the form to be sent to different email addresses based on which checkboxes were selected previously. For example, there is a question about the "Size of the company" with 2 che ...

Why is npm attempting to compile a previous version of my code?

Being a complete newbie to npm and node.js, I hope you can bear with me if I'm lacking in providing the right details. I am working on developing a plugin for a website that utilizes an out-of-the-box framework within npm. Initially, everything was ru ...

Implementing an Onclick function in HTML

I have an HTML code and I am looking to add an onclick event for a button named GET DATA. When the button is clicked, I want to send data for userId and categoryId to a PHP file. Can someone help me implement this functionality in my existing code? Here ...

Trigger Vue to scroll an element into view once it becomes visible

I created a dynamic form that calculates 2 values and displays the result card only after all values are filled and submitted, utilizing the v-if directive. Vuetify is my chosen UI framework for this project. This is the approach I took: <template> ...

Executing Laravel Ajax Requests on the whole website

I have been encountering an issue with my Ajax post call in my application. The call is supposed to update the Navigation throughout the entire site, but it seems to be working on some pages and not others. I am looking for a way to fix this and make it mo ...

Troubleshooting: jQuery.load function not functioning properly within ASP.NET MVC

I'm facing an issue with my code setup. Currently, I have the following components in different files: @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Home/index.html"))) This is included in my Razor file. <li><a href="#">Personal Re ...

Problem with routing: Request parameters not being collected

I am currently working on a project to create a wikipedia clone. Initially, I set up an edit route that looks like this: router.get('/edit/:id', function(req, res){ var id = req.params.id; console.log(id); models.Page.findById(id, ...

Troubleshooting issue with multer code failing to save files in designated directory within nodejs server when using reactjs frontend

I'm facing an issue while trying to upload a photo into my server folder. Even though the submission process adds the picture to my database, it does not display the image in my server folder. The frontend of my application is built using React JS, an ...

Dynamic Pagination with MUI Counting

I'm currently utilizing mui react for my current project. Within the Pagination component, I am required to input the count in order to display the total number of pages. For example, with a total of 27 products, and each page displaying 20 products ...

The code functions correctly on JSfiddle, however it is not executing properly on my website

When I tried to implement the code from this jsfiddle link: http://jsfiddle.net/mppcb/1/ on my website (), it didn't work as expected: Here is the HTML code snippet: <form id="myform" novalidate="novalidate"> <input type="text" name="fi ...

Upon loading the webpage, Firefox prompts the user to download the site

While my website functions properly on Internet Explorer, I encounter an issue when trying to open it on Firefox. Instead of opening the page, Firefox prompts me to download the file and opens the Download File dialog. This problem also occurs at times in ...

Guide to receiving intermediate feedback from my REST service for a standalone GET request

I have been working on designing a user interface that includes a progress bar to display the percentage of completion for a user request. However, my backend REST service performs complex computations and is relatively slow. I would like to provide the u ...

Is it possible for a Bootstrap modal dialog to overlay another dialog window?

<button class="btn" onClick="$('#firstModal').modal('show');">Click Here</button> <!-- Modal --> <div id="firstModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden=" ...

Error in Angular: Trying to access property 'setLng' of a null component variable

Just starting out with Angular and I've come across the error message Cannot read property 'setLng' of null. Can anyone help explain why this is happening? import { Component, OnInit, Input } from '@angular/core'; @Component({ ...

Refresh component when mobx store is modified

I am utilizing chart.js to display real-time price changes from the backend. The backend updates the frontend with new prices as they change, and stores the priceData (array) in a mobx store named priceChartStore. I need to continuously update the chart as ...