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

Restrict the character count in the input field according to its width

Is there a way to restrict the number of characters in an input field based on its width? I have a dynamic input field with varying widths and I would like users to be able to type without their text extending outside of the input boundary. Using maxLeng ...

Issue with margins of sections when attempting to activate menu class while scrolling

My Objective: I want to create a website where the menu highlights the section that is currently being viewed as the user scrolls up and down. Progress So Far: I have successfully implemented a functioning menu that changes to "active" when the correspo ...

Tips for preventing the loading of multiple local versions of jQuery

I have been struggling to prevent redundant loading of my local version of jQuery and jQuery UI due to the continuous Ajax pulls on the pages, which trigger a reload by jQuery each time. The specific jQuery files I am currently loading are: <script s ...

Having trouble extracting parameters from the router listen event in react-router?

Having trouble accessing the route parameter with react-router router.listen() method. It seems to fail, but I found a workaround using window.location.pathname.split('route/')[1]. Any suggestions? I've been investigating why this issue occ ...

Switching the menu based on screen size successfully functions for the div element, however, it does not

Currently, I am working on creating a responsive menu. The structure of my menu is set up as follows: HTML: <ul id="top-menu"> <li class="active"> <a href="#">HOME</a> </li> <li> <a href="#div2">ABOUT</ ...

Tips for effectively utilizing the :valid pseudo-class in Material-UI components to dynamically alter the border styling

Currently, I am attempting to adjust the border color of Mui TextFields using createTheme from Mui v5 when the input is valid. The border itself is defined within the ::before and ::after pseudoclasses. For the TextFields, I am utilizing variant="stan ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

Tips for gathering all links from a JSON object

When dealing with a JSON object of any structure, simple or complex, what would be the most efficient way to extract all URLs from the data and store them in an array for iteration in JavaScript? { "url": "https://example.com:443/-/m ...

The content in the footer is not displaying correctly (Vuejs)

I recently developed a component with a title and a background color meant to cover the entire page, but it seems to have a top margin that I can't seem to remove. Additionally, I created a footer component that should always stay at the bottom of the ...

Modifying Ajax-injected HTML with JQuery's editInPlace functionality

I have been successfully using the JQuery editInPlace plug-in on a static HTML page. However, I am facing an issue when trying to use the same plugin with HTML injected via an Ajax call. I have heard that using .on() like '$('.edit_inplace_fiel ...

The validation of radio input signals results in an error being returned

For a while now, I've been trying to solve the issue with radio button validation in my current project. Surprisingly, it works fine when there are no other functions in the form besides the radio buttons themselves. I suspect that the problem lies wi ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

Using a SASS watcher to keep an eye on every folder and compile them into a single CSS

I'm interested in setting up a folder structure like this: assets - scss - folder file.scss anotherfile.scss anotherfile.scss anotherfile.scss - anotherfolder file.scss anotherfile.scss anotherfile.scss ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

How can we show a div element when hovering over another element using css-in-js?

Is there a way to use material ui withStyles component in order to show information only on hover for a specific div? ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...

Set the current time to ISO8601 format

I need assistance with creating a "time passed" counter for my website based on an API call that returns data in the following format: "created_at": "2018-05-16T14:00:00Z", What is the best approach to calculate and display the time that has passed since ...

How to Change the Appearance of Elements in an Array Using React.js

My situation involves an array receiving data from an API, and I'm looking to customize each button's appearance by giving them different background colors. In addition, my project includes Material UI... Below is the snippet of code I have - {op ...

Encountering difficulties in sending a JavaScript array through jQuery ajax request

I'm feeling hesitant to ask this, but I can't figure out why my code isn't working. Here's what I have: <script> var formArray = new Array(); formArray['start'] = "one"; formArray['stopat'] = "two"; formArray ...