Spherelord
Spherelord

Reputation: 21

How to change CSS pseudo-class element using JavaScript

I want to change this image using javascript:

 dance:active { background-image: url("myImage.png") }

You can use

document.getElementById(element).style.backgroundImage = url(image);

to change

#element {background-image: url(image)}

I would like to change the image of when the element is active using javascript. Thanks!

Upvotes: 0

Views: 96

Answers (2)

XYZ
XYZ

Reputation: 27387

You can try using jQuery to achive what you want. dance: active is CSS Pseudo-classes. Learn more about Pseudo-class.

The demo change the div color when mouse down and switch the color back when mouse up. Leave comments if this is not what you want.

$("#dance").on("mousedown", function () {
    $("#dance").css("background", "blue");
}).on("mouseup", function(){
    $("#dance").css("background", "black");
});

https://jsfiddle.net/x_li/5nkvms8q/

and jQuery can also do the following

$('#damce:checked').val();

Upvotes: 0

Spherelord
Spherelord

Reputation: 21

I figured it out!

You can have multiple classes in your CSS :

element.dance1 { stuff }
element.dance1:active { active stuff }
element.dance2 { stuff 2 }
element.dance2:active { active stuff 2 }

and then change the class of the element in javascript:

document.getElementById(element).className = dance1/dance2

Upvotes: 1

Related Questions