HTML - Executing a script based on screen size
June 29, 2023
DD Planet
Sometimes it becomes necessary to execute a portion of the javascript or any other script for specific screen sizes only, i.e., for either small screens (mobile phones) or large screens (desktop or laptop).
Here are the tips and advice to help you execute a script based on screen sizes:
- A simple method would be to add a line based on the screen width, e.g. “if(screen.width <= 675) {“ would be used for screens with width less than 675px before the specified code. However, we cannot test whether this code is functioning by minimising the window size on a desktop or laptop.
- Another novel method that would be explained below is a bit better and can be tested even by varying the window sizes.
- In this method, we specify a new class that contains all the required changes that we wish to do for specific screens. For example, if we want to change the background image for mobile phones, we may specify a new class .mobilebg for small screens only and specify the new background image in it:
@media only screen and (max-width: 675px) {
.mobilebg { background-image: url(‘’); }}
- Then in the script, we shall add this new class mobilebg to the main class backg. For example, in the javascript, we shall specify
let main = document.getElementsByClassName(“backg”)[0];
If (document.body.scrollTop > 80 || document.documentElement,scrollTop > 80
{main.classList.add(“mobilebg”); } else {main.classList.remove(“mobilebg”);}
- The above code shall add the class ‘mobilebg’ to the main class ‘backg’ for small screens less than 675px when the page is scrolled and change the background at scroll only.