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.

13th Sep 2020, 9:23 AM
organic_042
organic_042 - avatar
4 Answers
+ 3
Organic For that you have to detect device or you can use @media attributes to set different colours for different devices.
13th Sep 2020, 9:25 AM
A͢J
A͢J - avatar
+ 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?
13th Sep 2020, 10:10 AM
Russ
Russ - avatar
+ 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.
13th Sep 2020, 10:03 AM
Divya Mohan
Divya Mohan - avatar
0
Russ Divya Mohan Thanks for answering, I will try both of these.
13th Sep 2020, 10:12 AM
organic_042
organic_042 - avatar