Petra Benelli Petra Benelli - 1 year ago 99
CSS Question

css - dynamically change background of pseudo element

I'm looking at dynamically changing background-color of header::before pseudo element. But also I'd like to only change background-color without having to create another class and define all other attributes for the 2nd time to switch between them only for one attribute that is different. Is it possible and if so, any suggestions?

HTML:

<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header></header>
</body>
<script src="code.js"></script>
</html>


CSS:

header {
position: absolute;
width: 100%;
height: 600px;
box-shadow: 0 0 10px black;
}

header::before {
content: "";
z-index: -1;
position: absolute;
width: inherit;
height: inherit;
background-color: red;

/*
few more attributes
*/
}


JS:

setInterval(function(){
var random = Math.floor((Math.random() * 5) + 1);

if(random == 1) console.log(1);// and also set header::before with background-color: blue;
else if(random == 2) console.log(2);// and also set header::before with background-color: green;
else console.log(3);// and also set header::before with background-color: red;
}, 2000);

Answer Source

using classes on header, you could create css for header.red::before etc, then change the header class as required? - a bit like

var hdr = document.querySelector('header');
setInterval(function() {
    var random = Math.floor((Math.random() * 5) + 1);

    if (random == 1) hdr.className = 'blue'; // and also set header::before with background-color: blue;
    else if (random == 2) hdr.className = 'green'; // and also set header::before with background-color: green;
    else hdr.className = 'red'; // and also set header::before with background-color: red;
}, 2000);
header {
    position: absolute;
    width: 100%;
    height: 600px;
    box-shadow: 0 0 10px black;
}

header::before {
    content: "";
    z-index: -1;
    position: absolute;
    width: inherit;
    height: inherit;
    background-color: red;
    /*
few more attributes
*/
}

header.red::before {
    background-color: red;
}
header.blue::before {
    background-color: blue;
}
header.green::before {
    background-color: green;
}
<header></header>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download