Changing the class name in HTML depending on the size of the screen

I'm attempting to dynamically change the class tag's name when a user visits the page based on the screen size. Below is the code snippet I've used:

<!DOCTYPE html>
<html>
<body onload="changeClass()">

<section class="example">
    <p>Hello</p>
</section>

<section class="example">
    <p>New section</p>
</section>

<script>
function changeClass() {
    var x = document.getElementsByClassName('example');
    var width = (window.innerHeight > 0) ? window.innerHeight : screen.Height;
    console.log(width);
    if(width <= 640) {
        while(x.length > 0) {
            x[1].className ='newClass'; 
        }
    } else {
        while(x.length > 0) {
            x[0].className = "example";
        }
    }
}
</script>
</body>
</html>

Unfortunately, the page enters an infinite loop and fails to load the data. Is there a simple way to set the class name based on the screen size? Can I use an "if conditional" statement when the page loads? I've included a link to a JSFiddle, but I'm unsure how much that will assist in resolving the issue.

Answer №1

To achieve the desired outcome, it is advisable to utilize media queries, as suggested in the comments.

Regarding your current code and question, you seem to be stuck in an infinite loop due to the usage of a while loop. The array length will never be reduced to zero, hence the loop will keep running indefinitely.

One possible solution is to replace the while loop with the following code snippet:

if(width <= 640) {
    for(var i = 0; i < x.length; i++) {
        x[i].className ='newClass'; 
    }
} 

Remember to modify both instances of the while loop in your code.

It is strongly advised to use media queries unless there is a specific reason not to. By simply adding a few lines to your stylesheet, you can adjust styles based on screen size:

@media (max-width: 640px) {
    .example {
        ... styles for smaller screens ...
    }
}

Answer №2

Your code has a couple of issues that need to be addressed. Firstly, the way you are retrieving the screen width is not correct.

It should be fixed as shown below:

var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;

Secondly, you do not need a loop at all. The following code snippet should be sufficient to achieve your goal:

function changeClass() {
    var x = document.getElementsByClassName('example');
    var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
    console.log(width);
    if(x.length > 0) {
        if(width <= 640) {
            x[1].className ='newClass'; 
        } else {
            x[0].className = "example";
        }
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jspsych: Centering and aligning 3 p tags to the left on the page

Feeling pretty stuck at the moment. Here's what I have visually right now: https://i.sstatic.net/FUzgM.png I added a caption in Comic Sans and an arrow using MS Paint. Each line with color swatches is wrapped in a p tag. The goal is to center thes ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Transferring input data between two HTML files in Electron with a secure login feature

Currently, I am in the process of developing an Electron app that facilitates communication between users through socket.io. The app includes a login screen where users can enter their registered email and password to access the main menu. For testing purp ...

HTML 4.01 character and character offset attributes

I'm curious about the purpose of the charoff attribute in HTML 4.01 Transitional. Specifically, consider a table column that contains the following cells: <td>1.30</td> <td>10</td> <td>100.2</td> <td>1000 ...

Intrigued by the prospect of making HTML elements vanish or smoothly glide along with the content without obstructing it

I'm a beginner in coding and I want to make my website impressive. Right now, I have an HTML embedded element called "On this Page" that I would like to disappear when the user scrolls down the page. I've managed to position the element on the ...

Icon dropdown in Bootstrap

Looking for a solution to modify this dropdown using only bootstrap classes. Instead of the current text "Dropleft" and left arrow icon, how can I replace it with an icon fas fa-ellipsis-h? <button type="button" class="btn btn-secondary ...

Conceal an element using a transition effect, initiating its positioning at the center instead of the default

One of the challenges I'm facing is with a video element that I want to hide gradually when clicking on another element. The issue is that after the animation completes, the video ends up hidden at the top-left corner of the screen instead of at the c ...

In a React/Redux component, there is a requirement to automatically fill a specified number of fields based on the selection made

Although this question is reminiscent of a previous one I asked, I have since restructured my project to incorporate Redux. Currently, I have a component that dynamically generates dropdown contents based on a data response from the app. One of the dropd ...

Display or Conceal Content Depending on the Button's Status

I am currently working on implementing an accordion style button for a project. I have configured my component to hide the list when the button is clicked, but I am encountering an issue where the list does not reappear. Additionally, I would like to inc ...

Get rid of the margins on your Wordpress theme

Currently, my Wordpress site is using the Tesseract theme which can be found at (http:// instantiwebs . com) I am interested in removing the left/right margins on all elements, similar to what has been done on this website: . Interestingly enough, they al ...

The NextJs image entered into an endless loop, throwing an error message that said: "The 'url' parameter is correct, but the response from the

I have been using next/image component with next js version ^12.2.3-canary.17 for my current project. The issue I am encountering is that some images are missing from the source directory, resulting in infinite error logs like the one shown below: https:/ ...

Issue with ngModelChange and change events not functioning properly in Internet Explorer 11

Within a text input field, I have implemented single-way binding in addition to utilizing a number formatter pipe. I have also set up an (ngModelChange) event handler to remove any commas that are added by the number formatter, and a (change) event to tri ...

Looking for a never-ending whiteboard experience with React that includes zoom, pan, and pinch functionality

Recently, I put together a flow chart with the help of the npm package react-zoom-pan-pinch Issue : One problem I encountered is that the chart has boundaries on the left and top, while appearing infinite on the right and bottom. Is there a way to expan ...

JQuery animations not functioning as expected

I've been attempting to create a functionality where list items can scroll up and down upon clicking a link. Unfortunately, I haven't been able to achieve the desired outcome. UPDATE: Included a JSFiddle jQuery Code: $(document).ready(function ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Express.js code is experiencing difficulties with autocomplete functionalities

jQuery autocomplete code example [Express JS code for retrieving data][2\ Example of fetching data in Express JS ...

Grabbing the HTML value and storing it in a JavaScript variable

In my table, each row has multiple columns including one with a checkbox. When this checkbox is checked, a new column cell appears to the right of the table with an up/down spinner to adjust a value. The issue I'm facing is that I want to limit the s ...

Ways to include additional assurances depending on a specific circumstance

When my code is executed in edit mode, I have a selection of API calls that need to be made, as well as one specific API call that must be made in both create and edit modes. Here is the current code snippet: // other controller code var config = {}; ...

Restricting the download of data in Firebase when using the

I have implemented a Firestore listener in my app that downloads items from the database as they are added. Initially, all documents are downloaded using onSnapshot, but I want to limit this to 12 items as I am using a FlatList to render items as I scroll. ...

Utilize esbuild to load Bootstrap JavaScript libraries

I have been attempting to incorporate the bootstrap JS into my esbuild setup: // index.js import 'jquery-import' import 'bootstrap' // jquery-import.js import jquery from 'jquery' window.jQuery = window.$ = jquery; The build ...