STL34
STL34

Reputation: 355

Changing hover background color with javascript

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?

Upvotes: 0

Views: 12320

Answers (4)

Kalle H. V&#228;ravas
Kalle H. V&#228;ravas

Reputation: 3615

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>

Upvotes: 2

Rene van der Lende
Rene van der Lende

Reputation: 5281

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?

Upvotes: 2

Unmitigated
Unmitigated

Reputation: 89194

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>

Upvotes: 0

Stark Jeon
Stark Jeon

Reputation: 1145

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

Upvotes: 3

Related Questions