0

I want to access the hover background color of a button to change the hover background color every time the button is clicked.

This is the button tag from the index.html file

<button class="btn-hero btn-hero:hover" id="btn">click me</button>

This is in the css file:

.btn-hero {
  font-family: var(--ff-primary);
  text-transform: uppercase;
  background: transparent;
  color: var(--clr-black);
 
}
.btn-hero:hover {
  color: var(--clr-white);
  background: var(--clr-black);
}

I can access the button background color like this:

btn.addEventListener("click", function () {

btn.style.backgroundColor = 'some_color'

});

That changes the button color but negates the hover property.

I tried doing this in the app.js:

let button_hover = document.querySelector(".btn-hero:hover")

But that returns a null.

Is there a way to do access the hover properties from the css file in app.js file?

STL34
  • 315
  • 3
  • 6
  • 15
  • Does this answer your question? [Change :hover CSS properties with JavaScript](https://stackoverflow.com/questions/11371550/change-hover-css-properties-with-javascript) – nip Jul 31 '20 at 19:23
  • No. That answer hard codes the css file via javascript. I'm trying to change a pseudo element in the css file via an eventListener when a button is clicked. – STL34 Aug 01 '20 at 17:00
  • @nip Sorry. You're right. That is the correct way to do what I was trying to do. – STL34 Aug 04 '20 at 14:36

4 Answers4

3

Answer

In terms of javascript you can use mouseover event handler

Example

btn.addEventListener("mouseenter", function( event ) {   
  event.target.style.color = "purple";
}, false);
btn.addEventListener("mouseleave", function( event ) {   
  event.target.style.color = "";
}, false);

Reference

MDN : mouseover event

Stark Jeon
  • 1,107
  • 9
  • 24
2

The snippets your posted contain a few errors in both the JS and the HTML:

HTML

  • <button class="btn-hero" id="btn">click me</button> should not contain :hover as this is a CSS pseudo selector (in this case connected to btn-hero) and should only be used in CSS (or referenced by Javascript). Remove the btn-hero:hover.

Javascript

  • If you want to 'catch' the element hover event you need to attach an eventListener (in case of hover either mouseover or mouseenter) to the button

  • While document.querySelector(".btn-hero:hover") is a proper selector, but due to the asynchrous nature of Javascript it would be purely accidental that the hover would be caught when the JS function runs. That is why the function returns NULL.

  • If you want to modify the CSS style of an element, digg into MDN: Window.getComputedStyle()

CSS

Seems okay to me.

Your question

Please make sure you understand that the hex value of a color is essentially not one long hexadecimal value, but a concatenation of 3 hex values resembling R,G,B made up of 2 hexadecimal digits each. Adding 100hex to any #xxxxxx (6 digit) color would get rather unexpected results. Which of the three (R,G,B) do you want to change?

Rene van der Lende
  • 4,992
  • 2
  • 14
  • 25
  • I've edited the code snippet with an eventListener. I still can't change :hover's background though. – STL34 Aug 01 '20 at 17:09
  • Thanks for the clarification on what the hex values of colors are. I want to make the background color of a button change through a spectrum of colors as it's clicked. – STL34 Aug 01 '20 at 17:17
  • 1
    While `Window.getComputedStyle()` is read-only, in an eventListener you can anticipate on its values. If you want to do some fun stuff with a 'color-spectrum', you might want to have a look at the CSS `hsl()` and `hsla()` color functions. Manipulating the 'hue', 'saturation' and 'lightness' (esp. 'hue') of a color is much easier than converting back and forth between hex and dec values. Also check/toy with the CSS `filter: hue-rotate()` – Rene van der Lende Aug 01 '20 at 22:53
2

So you want each button click to change the background a bit. I did not understand your hex point, but here is one of the scripts, that calculates background color from given numeric value. In this case its the attribute data-colorvalue

I modified it to fit your case and made it so it adds 10 each click. You can play around the math here, that way you get different colors:

// Grab the button:
const btn = document.querySelector('#btn')

// Detect on click event:
btn.onclick = e => {
    
    // Get the buttons color value, parseInt makes sure its INT:
    let color_value = parseInt(btn.getAttribute('data-colorvalue'))
    
    // Make the R value based on color_value:
    val_r = Math.round((255 * color_value) / 100)
    
    // Make the G value based on color_value:
    val_g = Math.round((255 * (100 - color_value)) / 100)
    
    // Make the B value based on color_value:
    val_b = Math.round(255 - (color_value * 1.5))
    
    // Format and set as buttons background:
    btn.style.backgroundColor = 'rgb(' + val_r + ', ' + val_g + ', ' + val_b + ')'
    
    // Set the new color value plus 10.. you can play with this formula:
    btn.setAttribute('data-colorvalue', color_value + 10)
}
<button id="btn" data-colorvalue="1">Click me</button>

If you want to change the hover as pseudo, then you need magic. And thats a completely standalone quesiton.

Your title says text color and question background, color. So if you want to change the text / font color you simply use btn.style.color instead of backgroundColor.

Psedo classes do not go to your html like so, ever:
enter image description here

EDIT

Based on the additional information provided in the comments, we worked out, that you want to change the hover-background-color each time the button is clicked.

This is a very strange situation and odd request. But one of the ways doing it is making new style element contents on each click like so:

// Grab the button:
const btn = document.querySelector('#btn')

// Make style element:
let style = document.createElement('style')

// Detect on click event:
btn.onclick = e => {
    
    // Get the buttons color value, parseInt makes sure its INT:
    let color_value = parseInt(btn.getAttribute('data-colorvalue'))
    
    // Make the R value based on color_value:
    val_r = Math.round((255 * color_value) / 100)
    
    // Make the G value based on color_value:
    val_g = Math.round((255 * (100 - color_value)) / 100)
    
    // Make the B value based on color_value:
    val_b = Math.round(255 - (color_value * 1.5))
    
    // Set the new color value plus 10.. you can play with this formula:
    btn.setAttribute('data-colorvalue', color_value + 10)
    
    // Now starts the magic...  
    // Make the css contents for the style element:
    let css = '#btn:hover{background-color:rgb(' + val_r + ', ' + val_g + ', ' + val_b + ')}'
    
    // If style element exists already, then lets overwrite its contents:
    if (style != undefined) style.innerHTML = css
    
    // .. however if there is none, then we must append new:
    else style.appendChild(document.createTextNode(css))
    
    // Now we simply append the style element to the head:
    document.getElementsByTagName('head')[0].appendChild(style)
}
<button id="btn" data-colorvalue="1">Click me</button>
Kalle H. Väravas
  • 3,579
  • 4
  • 30
  • 47
  • Thanks for the feedback. I tried adding that "magic" to my code and it did not work. Changing/editing already existing css pseudo classes via javascript, namely the background color of a button when it's hovered over and clicked on appears to be impossible. – STL34 Aug 03 '20 at 16:14
  • Why do you want to change the hover color via javascript? Explain the context? What are you trying to do? – Kalle H. Väravas Aug 03 '20 at 16:16
  • It would be an interesting effect and the fact that I can't make it work makes me want to make it work. The non hover and hover colors are different. I can change the non hover color with a button click. I want to be able to change the hover color with a button click too. – STL34 Aug 03 '20 at 16:25
  • Do I understand you correctly. You want to change a little bit of hover background color, each time the button is clicked? Not the background, but hover background specifically. Each time the user clicks the button? Does the example I gave work in the matter, that the color changes every click -- so that but not for the background, but hover background? – Kalle H. Väravas Aug 03 '20 at 16:27
  • Yes. That's exactly what I'm trying to do. – STL34 Aug 03 '20 at 16:29
  • 1
    Check out the edit on the answer. Its not ideal, but the requirement is very weird to start with.. but in theory this is one way to do it.. To be honest, I cannot imagine any other ways. – Kalle H. Väravas Aug 03 '20 at 17:10
0

You can use !important, but you may want to refactor your code by setting CSS variables with JavaScript or using mouseenter and mouseleave event handlers.

const btn = document.querySelector('#btn');
btn.style.backgroundColor = 'red'
:root {
  --clr-black: black;
  --clr-white: white;
}

.btn-hero {
  font-family: var(--ff-primary);
  text-transform: uppercase;
  background: transparent;
  color: var(--clr-black);
 
}
.btn-hero:hover {
  color: var(--clr-white);
  background: var(--clr-black) !important;
}
<button class="btn-hero" id="btn">click me</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80