How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don’t know of a .style JavaScript equivalent for :hover.
asked Jul 7, 2012 at 1:27
zdebruinezdebruine
3,4976 gold badges29 silver badges50 bronze badges
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
answered Jul 7, 2012 at 1:37
kennebeckennebec
102k32 gold badges105 silver badges127 bronze badges
6
You can’t change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).
answered Jul 7, 2012 at 1:30
Achal DaveAchal Dave
3,9092 gold badges24 silver badges32 bronze badges
3
Pretty old question so I figured I’ll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP’s example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here’s a working example https://codepen.io/ybentz/pen/RwPoeqb
answered Feb 22, 2020 at 23:08
ybentzybentz
4444 silver badges12 bronze badges
2
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element’s class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|s)oldClass(?!S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\s)' + oldClass + '(?!\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
answered May 18, 2013 at 15:42
isgoedisgoed
6646 silver badges11 bronze badges
0
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
answered Aug 18, 2019 at 12:58
2
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
answered May 21, 2016 at 17:49
3
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
answered Oct 19, 2020 at 14:08
1
I’d recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
answered Jul 4, 2017 at 12:06
Shobhit SharmaShobhit Sharma
5941 gold badge8 silver badges18 bronze badges
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I’m a novice, so take it for what it’s worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to «hoverCell».
answered Jun 5, 2016 at 19:57
elPastorelPastor
8,16511 gold badges53 silver badges80 bronze badges
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
answered Sep 3, 2016 at 10:52
Tero TolonenTero Tolonen
4,0844 gold badges26 silver badges31 bronze badges
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td‘s
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
random-parts
2,1192 gold badges12 silver badges20 bronze badges
answered Oct 23, 2017 at 21:45
1
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
answered May 4, 2022 at 7:49
0
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven’t found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
answered May 21, 2020 at 23:28
cs1349459cs1349459
8518 silver badges27 bronze badges
Had some same problems, used addEventListener for events «mousenter», «mouseleave»:
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
answered Feb 20, 2021 at 21:21
1
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
@click="form1()">
Login
</button>
TylerH
20.5k62 gold badges75 silver badges97 bronze badges
answered Feb 20, 2022 at 21:56
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
answered Feb 23, 2022 at 10:00
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
answered Dec 21, 2022 at 2:06
1
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
answered Jul 9, 2020 at 14:27
baudo2048baudo2048
1,10214 silver badges27 bronze badges
How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don’t know of a .style JavaScript equivalent for :hover.
asked Jul 7, 2012 at 1:27
zdebruinezdebruine
3,4976 gold badges29 silver badges50 bronze badges
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
answered Jul 7, 2012 at 1:37
kennebeckennebec
102k32 gold badges105 silver badges127 bronze badges
6
You can’t change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).
answered Jul 7, 2012 at 1:30
Achal DaveAchal Dave
3,9092 gold badges24 silver badges32 bronze badges
3
Pretty old question so I figured I’ll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP’s example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here’s a working example https://codepen.io/ybentz/pen/RwPoeqb
answered Feb 22, 2020 at 23:08
ybentzybentz
4444 silver badges12 bronze badges
2
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element’s class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|s)oldClass(?!S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\s)' + oldClass + '(?!\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
answered May 18, 2013 at 15:42
isgoedisgoed
6646 silver badges11 bronze badges
0
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
answered Aug 18, 2019 at 12:58
2
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
answered May 21, 2016 at 17:49
3
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
answered Oct 19, 2020 at 14:08
1
I’d recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
answered Jul 4, 2017 at 12:06
Shobhit SharmaShobhit Sharma
5941 gold badge8 silver badges18 bronze badges
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I’m a novice, so take it for what it’s worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to «hoverCell».
answered Jun 5, 2016 at 19:57
elPastorelPastor
8,16511 gold badges53 silver badges80 bronze badges
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
answered Sep 3, 2016 at 10:52
Tero TolonenTero Tolonen
4,0844 gold badges26 silver badges31 bronze badges
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td‘s
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
random-parts
2,1192 gold badges12 silver badges20 bronze badges
answered Oct 23, 2017 at 21:45
1
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
answered May 4, 2022 at 7:49
0
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven’t found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
answered May 21, 2020 at 23:28
cs1349459cs1349459
8518 silver badges27 bronze badges
Had some same problems, used addEventListener for events «mousenter», «mouseleave»:
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
answered Feb 20, 2021 at 21:21
1
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
@click="form1()">
Login
</button>
TylerH
20.5k62 gold badges75 silver badges97 bronze badges
answered Feb 20, 2022 at 21:56
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
answered Feb 23, 2022 at 10:00
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
answered Dec 21, 2022 at 2:06
1
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
answered Jul 9, 2020 at 14:27
baudo2048baudo2048
1,10214 silver badges27 bronze badges
How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don’t know of a .style JavaScript equivalent for :hover.
asked Jul 7, 2012 at 1:27
zdebruinezdebruine
3,4976 gold badges29 silver badges50 bronze badges
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
answered Jul 7, 2012 at 1:37
kennebeckennebec
102k32 gold badges105 silver badges127 bronze badges
6
You can’t change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).
answered Jul 7, 2012 at 1:30
Achal DaveAchal Dave
3,9092 gold badges24 silver badges32 bronze badges
3
Pretty old question so I figured I’ll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP’s example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here’s a working example https://codepen.io/ybentz/pen/RwPoeqb
answered Feb 22, 2020 at 23:08
ybentzybentz
4444 silver badges12 bronze badges
2
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element’s class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|s)oldClass(?!S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\s)' + oldClass + '(?!\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
answered May 18, 2013 at 15:42
isgoedisgoed
6646 silver badges11 bronze badges
0
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
answered Aug 18, 2019 at 12:58
2
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
answered May 21, 2016 at 17:49
3
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
answered Oct 19, 2020 at 14:08
1
I’d recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
answered Jul 4, 2017 at 12:06
Shobhit SharmaShobhit Sharma
5941 gold badge8 silver badges18 bronze badges
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I’m a novice, so take it for what it’s worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to «hoverCell».
answered Jun 5, 2016 at 19:57
elPastorelPastor
8,16511 gold badges53 silver badges80 bronze badges
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
answered Sep 3, 2016 at 10:52
Tero TolonenTero Tolonen
4,0844 gold badges26 silver badges31 bronze badges
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td‘s
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
random-parts
2,1192 gold badges12 silver badges20 bronze badges
answered Oct 23, 2017 at 21:45
1
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
answered May 4, 2022 at 7:49
0
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven’t found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
answered May 21, 2020 at 23:28
cs1349459cs1349459
8518 silver badges27 bronze badges
Had some same problems, used addEventListener for events «mousenter», «mouseleave»:
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
answered Feb 20, 2021 at 21:21
1
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
@click="form1()">
Login
</button>
TylerH
20.5k62 gold badges75 silver badges97 bronze badges
answered Feb 20, 2022 at 21:56
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
answered Feb 23, 2022 at 10:00
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
answered Dec 21, 2022 at 2:06
1
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
answered Jul 9, 2020 at 14:27
baudo2048baudo2048
1,10214 silver badges27 bronze badges
How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don’t know of a .style JavaScript equivalent for :hover.
asked Jul 7, 2012 at 1:27
zdebruinezdebruine
3,4976 gold badges29 silver badges50 bronze badges
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
answered Jul 7, 2012 at 1:37
kennebeckennebec
102k32 gold badges105 silver badges127 bronze badges
6
You can’t change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, @Bryan).
answered Jul 7, 2012 at 1:30
Achal DaveAchal Dave
3,9092 gold badges24 silver badges32 bronze badges
3
Pretty old question so I figured I’ll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP’s example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here’s a working example https://codepen.io/ybentz/pen/RwPoeqb
answered Feb 22, 2020 at 23:08
ybentzybentz
4444 silver badges12 bronze badges
2
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element’s class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|s)oldClass(?!S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\s)' + oldClass + '(?!\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
answered May 18, 2013 at 15:42
isgoedisgoed
6646 silver badges11 bronze badges
0
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
answered Aug 18, 2019 at 12:58
2
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
answered May 21, 2016 at 17:49
3
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
answered Oct 19, 2020 at 14:08
1
I’d recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
answered Jul 4, 2017 at 12:06
Shobhit SharmaShobhit Sharma
5941 gold badge8 silver badges18 bronze badges
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I’m a novice, so take it for what it’s worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to «hoverCell».
answered Jun 5, 2016 at 19:57
elPastorelPastor
8,16511 gold badges53 silver badges80 bronze badges
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
answered Sep 3, 2016 at 10:52
Tero TolonenTero Tolonen
4,0844 gold badges26 silver badges31 bronze badges
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td‘s
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
random-parts
2,1192 gold badges12 silver badges20 bronze badges
answered Oct 23, 2017 at 21:45
1
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
answered May 4, 2022 at 7:49
0
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven’t found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
answered May 21, 2020 at 23:28
cs1349459cs1349459
8518 silver badges27 bronze badges
Had some same problems, used addEventListener for events «mousenter», «mouseleave»:
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
answered Feb 20, 2021 at 21:21
1
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
@click="form1()">
Login
</button>
TylerH
20.5k62 gold badges75 silver badges97 bronze badges
answered Feb 20, 2022 at 21:56
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
answered Feb 23, 2022 at 10:00
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
answered Dec 21, 2022 at 2:06
1
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
answered Jul 9, 2020 at 14:27
baudo2048baudo2048
1,10214 silver badges27 bronze badges
Introduction
Working with visuals is an excellent way to keep our interface interactive and to capture the user’s attention. Having objects animated on our screen creates a unique experience and increases interactivity.
In this article, we will learn how to style hover in React using CSS, as well as how to do inline hover styling.
Hover is a pseudo-class that simply allows us to add specific styles to make a user aware when their mouse is on and off a specific element. For this article, we’ll use a box:
const App = () => {
return (
<div>
<div className="box">
<p>Hover me!</p>
</div>
</div>
);
};
which has this basic styling:
.box {
height: 200px;
width: 200px;
background-color: rgb(0, 191, 255);
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
cursor: pointer;
}
Essentially, we’ll change the background color to lightblue when the mouse is over the box and then return it to its default style when the mouse is removed.
How to Style Hover in React
There are two approaches to this: external and inline. External involves having a separate CSS file that makes it easy to style for hover, whereas inline styling does not allow us to style with pseudo-class, but we will learn how to style hover in inline CSS by using mouse events in this article.
How to Style Hover in React With CSS External Styling
This is very similar to how HTML and CSS work; all we have to do is give the element a className (not class) or use the tag as the selector which we would target and then style the hover pseudo class:
.box {
height: 200px;
width: 200px;
background-color: rgb(0, 191, 255);
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
cursor: pointer;
}
.box:hover {
background-color: lightblue;
}
All we did was add the :hover pseudo class to the previously styled selector and change any of the properties we wanted to change when the mouse was over the element.
How to Style Hover in React With Inline Styling
By inline styling, we mean styling via the element’s tag, which is accomplished with the style attribute. If we want to convert the preceding code to inline styling:
const App = () => {
return (
<div>
<div
style={{
height: '200px',
width: '200px',
backgroundColor: 'rgb(0, 191, 255)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '30px',
cursor: 'pointer',
}}
>
<p>Hover me!</p>
</div>
</div>
);
};
Having styles like this repeated within our App could make it difficult to read, so we could create a style object if we’re only styling a single object on a page, and there’s no need in creating a file for it:
const App = () => {
const boxStyle = {
height: '200px',
width: '200px',
backgroundColor: 'rgb(0, 191, 255)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '30px',
cursor: 'pointer',
};
return (
<div>
<div style={boxStyle}>
<p>Hover me!</p>
</div>
</div>
);
};
So far, we’ve built our box. To style hover with inline CSS in React, we conditionally set inline styles using a state, as well as the onMouseEnter and onMouseLeave props, which tell us when the mouse is on the element and when it is not:
import { useState } from 'react';
const App = () => {
const [isHover, setIsHover] = useState(false);
const handleMouseEnter = () => {
setIsHover(true);
};
const handleMouseLeave = () => {
setIsHover(false);
};
const boxStyle = {
<!-- ... -->
};
return (
<div>
<div
style={boxStyle}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<p>Hover me!</p>
</div>
</div>
);
};
At this point, we can conditionally style any property using the *isHover* state:
const boxStyle = {
//...
backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)',
};
So far, we’ve seen how to implement it. Now, let’s break down our code and explain why we used the syntax we did. We began by creating a state that stores a boolean value indicating when hovering occurs (true) and otherwise (by default it’s set to false):
const [isHover, setIsHover] = useState(false);
We then also added two events to the div to help change our state and know when the mouse is on the box and when it’s off the box:
<div
style={boxStyle}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<p>Hover me!</p>
</div>
The onMouseEnter event is triggered when the mouse enters the element, while the onMouseLeave event is triggered when it leaves. We assigned a function to each of these events, which we now use to change the state:
const handleMouseEnter = () => {
setIsHover(true);
};
const handleMouseLeave = () => {
setIsHover(false);
};
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
We set the state in each function based on the triggered event. Finally, we can use the state to conditionally style the box not only for backgroundColor, but also for any other style:
const boxStyle = {
//...
backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)',
color: isHover ? 'red' : 'green',
};
When we put all this together, we are now able to style hover in React with Inline style:
import { useState } from 'react';
const App = () => {
const [isHover, setIsHover] = useState(false);
const handleMouseEnter = () => {
setIsHover(true);
};
const handleMouseLeave = () => {
setIsHover(false);
};
const boxStyle = {
height: '200px',
width: '200px',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
fontSize: '30px',
cursor: 'pointer',
backgroundColor: isHover ? 'lightblue' : 'rgb(0, 191, 255)',
color: isHover ? 'red' : 'green',
};
return (
<div>
<div
style={boxStyle}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<p>Hover me!</p>
</div>
</div>
);
};
export default App;
Conclusion
We learned how to style hover in React using both external styling and inline styling in this article. Though inline styling is not recommended, it is useful to understand how it works in case we are prompted to use it.
By
rus · Posted December 17, 2022
html:
<td>
<span class=»qty-minus» onclick=»qtyMinus(); return false;» data-id=»<?=$id;?>» data-qty=»<?= $item[‘qty’];?>» data-weight=»<?=$item[‘weight’];?>»>
<i class=»bi bi-dash-circle-fill text-success»></i>
</span>
<span class=»qty»><?= $item[‘qty’];?></span>
<span class=»qty-plus» onclick=»qtyPlus(); return false;» data-id=»<?=$id;?>» data-qty=»<?= $item[‘qty’];?>» data-weight=»<?=$item[‘weight’];?>»>
<i class=»bi bi-plus-circle-fill text-success»></i>
</span>
</td>
js:
// Изменение количества товара в заказа — плюс
function qtyPlus() {
$(‘.qty-plus’).on(‘click’, function(){
let str = $(this).data(‘id’);
if(typeof str === ‘string’){
let id_arr = str.split(‘-‘),
id = id_arr[0],
mod = id_arr[1],
qty_update = $(this).data(‘qty’)+1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}else if(!Number.isNaN(str)){
let id = $(this).data(‘id’),
mod = null,
qty_update = $(this).data(‘qty’)+1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}
});
return true;
}
// Изменение количества товара в заказа — минус
function qtyMinus() {
$(‘.qty-minus’).on(‘click’, function(){
let str = $(this).data(‘id’);
if(typeof str === ‘string’){
let id_arr = str.split(‘-‘),
id = id_arr[0],
mod = id_arr[1],
qty_update = $(this).data(‘qty’)-1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}else if(!Number.isNaN(str)){
let id = $(this).data(‘id’),
mod = null,
qty_update = $(this).data(‘qty’)-1,
weight = $(this).data(‘weight’);
$.ajax({
url: ‘/cart/add’,
data: {id: id, qty_update: qty_update, mod: mod, weight:weight},
type: ‘GET’,
success: function(res){
showCart(res);
},
error: function(){
alert(‘Ошибка! Попробуйте позже’);
}
});
}
});
return true;
}
Суть в том, что клик срабатывает только со второго раза… Почему?
Страница: https://shop-site.su/category/men
Нужно положить товар в корзину и либо в модальном окне, либо перейти на страницу оформления заказа (а лучше и там и там покликать) и покликать на плюс и минус кол-ва товара.
Решил проблему:
убрал из html вызов функции onclick=»qtyMinus(); return false;»
а js переделал вот так:
$(‘body’).on(‘click’, ‘.qty-minus’, function(){…});
Но вот ответ на вопрос почему, все же хотелось бы знать.
