0
How to change css styles using JavaScript?
I want to change the CSS style using JavaScript but the styles should change differently based on the screen size. For example: There is a button on the website that changes the color of the page and if the click the button on the desktop the color should become red and if I press the same button on mobile then the color should become green.
4 Answers
+ 3
Organic For that you have to detect device or you can use @media attributes to set different colours for different devices.
+ 3
Not sure on A J #Level 20 's answer, but on my device at least, you can get the screen width by simply using screen.width.
let body = document.getElementsByTagName("body")[0];
if (screen.width < 500) {
body.style.backgroundColor = "green";
} else if (screen.width < 800) {
body.style.backgroundColor = "blue";
} else {
body.style.backgroundColor = "red";
}
Something like this?
+ 2
It seems somewhat more related to media query
(A tool of CSS)
By the way you can do it with js also.
Use innerHeight property with if condition and event listener on button.
Rough idea.
If(screenWidth<450px) {
Button. Addeventlistener("click", () =>{
document. Body. Background="red";
}) ;
else if(screenWidth>850px) {
Button. Addeventlistener("click", () =>{
document. Body. Background="green";
}) ;
This is rough idea đĄ
Shape it accordingly.
0
Russ Divya Mohan Thanks for answering, I will try both of these.