Changing the screen size will add or remove a class

My current project utilizes the Bulma CSS framework along with raw Javascript. I am facing an issue where I need to remove the "is-pulled-right" class on mobile screen sizes. However, I've noticed that only the first element seems to respond to the script, while the others are being overlooked. Can someone please point out what mistake I might be making?

window.addEventListener("resize", function () {

    const classList = document.getElementById("isRight").classList
    
    if(window.innerWidth < 820) {   
        classList.remove("is-pulled-right")
    } 

    else{
        classList.add("is-pulled-right");
    }

});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10535049484e1c51555a4843495f4d54511208151e1203">[email protected]</a>/css/bulma.min.css" rel="stylesheet"/>
<section class="section">

  <div class="container">
    <div class="columns">
      <div class="column is-two-fifths">
        <h3 id="isRight" class="subtitle is-3 is-pulled-right ">First Title:</h3>
      </div><!-- column left-->
      <div class="column">
        <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque...
      </div><!-- column right -->
    </div><!-- columns -->
  </div><!-- container -->
  
</section>

<section class="section">

  <div class="container">
    <div class="columns">
      <div class="column is-two-fifths">
        <h3 id="isRight" class="subtitle is-3 is-pulled-right ">Second Title:</h3>
      </div><!-- column left-->
      <div class="column">
        <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque... 
      </div><!-- column right -->
    </div><!-- columns -->
  </div><!-- container -->
  
</section>

Answer №1

When creating elements in HTML, it is important to ensure that the ID attribute is unique. Instead of using the same ID for multiple elements, consider using classes to differentiate between them.


If you need to select all elements with a specific class, you can use the document.querySelectorAll method. This allows you to target elements by their class name rather than relying on IDs.

    const classList = document.querySelectorAll(".is-pulled-right")
    
window.addEventListener("resize", function () {

    if(window.innerWidth < 700) {   
        classList.forEach( item => {
        item.classList.remove("is-pulled-right")})
    } 
 
    else{
      console.log('more')
        classList.forEach( item => {
        item.classList.add("is-pulled-right")})
    }
}); 
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b190e17161a3b4b55425548">[email protected]</a>/css/bulma.min.css" rel="stylesheet"/>
<section class="section">

  <div class="container">
    <div class="columns">
      <div class="column is-two-fifths">
        <h3 id="isRight" class="subtitle is-3 is-pulled-right ">First Title:</h3>
      </div><!-- column left-->
      <div class="column">
        <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, ..."</p>
      </div><!-- column right -->
    </div><!-- columns -->
  </div><!-- container -->
  
</section>

<section class="section">

  <div class="container">
    <div class="columns">
      <div class="column is-two-fifths">
        <h3 id="isRight" class="subtitle is-3 is-pulled-right ">Second Title:</h3>
      </div><!-- column left-->
      <div class="column">
        <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem..."</p>
      </div><!-- column right -->
    </div><!-- columns -->
  </div><!-- container -->
  
</section>

Answer №2

Utilize JavaScript to implement an event listener for adding multiple events on the window.

const container = document.getElementById("isRight")

window.onresize = function(){
    if(window.innerWidth < 820) {   
        container.classList.remove("is-pulled-right")
    } else {
        container.classList.add("is-pulled-right");
    }
}

Answer №3

It is not recommended to have multiple duplicate IDs as they should be unique. This is why document.getElementById(id); only retrieves one element.

Instead of using IDs, consider using classes. You can then use something like this method.

If it's not possible to remove the IDs, you can try the following approach:

Array.from(document.querySelectorAll('#isRight')).map(e => e.classList).forEach(classlist => {
    // your logic for classList
})

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

Node.js server only supports cross-origin requests for protocol schemes when working with an Angular front end

Struggling to configure CORS on a local site hosting a Node.js server and an Angular client. Encountering the following error: Access to XMLHttpRequest at 'localhost:3000/api/v1/users' from origin 'http://localhost:4200' has been bl ...

"Enhance Your Text Fields with Angular2 Text Masks for Added Text Formatting

Is there a way to combine text and numbers in my mask? This is what I am currently using: [/\d/, /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/] The above code only allows for numbers. How can I modify it to allow f ...

Strategies for developing versatile controls that can adapt to the environment in which they are used?

Take a look at the image provided. In my application, I have three large black rectangles representing different forms in separate contexts. Across all three forms, there is a red box control present. The visibility and values of this red box are determin ...

Authenticating with passportjs using a Google Apps email address for verification

I am currently experimenting with using Passport.js along with a Google Apps email ID. I have successfully been able to authenticate using a gmail.com email ID, however, I am facing challenges when attempting to authenticate if the email ID is associated w ...

Redis appears to be missing the expected results

After following an express demo which involved storing and retrieving values with Redis, I attempted to implement the code in my own Express app. However, I encountered issues as the req.online variable was returning null when I tried to retrieve its lengt ...

Combining DataTables with multiple tables sourced from various JSON arrays

I am trying to display data from two different arrays within the same JSON source in two separate tables, but my code seems to be malfunctioning. JSON Information: { "Policies": [ { "name": "A", "id": "1", "score": "0" } ], ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

Tips for handling the accent mark (diacritic mark)

My primary language is Spanish, which means I use accent marks quite frequently (á, é...). When I need to type them out, I resort to using &aacute;, &eacute;, and so on. However, I'm facing an issue when trying to compare two sentences in m ...

What is the best location for storing css files in Laravel?

I've come to realize that I can easily make changes to the app.scss file in my Laravel projects and see those changes reflected by running npm run dev or npm run watch. However, I'm faced with a dilemma when dealing with multiple .css files. Whe ...

What is the best way to retrieve a specific children element from a JSON object in JavaScript based on a keyname and value match

Recently, I encountered a JSON data structure that looked like this: var jsonData = { "id": 0, "content": "abc", "children" : [{ "id": 1, "content": "efg", "children" : [] } { "id": 2, "c ...

Utilize multiple buttons to toggle with v-if condition

Here's the code snippet I'm working with: <div class="flex justify-between flex-wrap"> <div v-for="kink in kinks.data" :key="kink.id"> <button type="button" :class="enabl ...

Issue: Having trouble making the frontend work properly due to difficulty in accessing the 'state' property which is undefined

Encountering an issue while attempting to input data from a web application into the database. Having trouble understanding the root cause of the problem. The error occurs when the database insert button is triggered. The following snippets of code showcas ...

Guide to establishing a primary filter for my Json information with Angular.js?

After spending multiple days searching and reading, I am struggling to set an initial value for the data from a Rails JSON file in my application. The app focuses on incident tickets, and although I am able to retrieve all entries from the database using d ...

Material UI Card shadow effect getting cropped

Currently experiencing an uncommon issue while using Material UI's Card component - the box-shadow is cut off on the top and bottom sides. Any suggestions on how to resolve this problem? Check out my code below: import React, { Component } from & ...

Unable to display a recursive component with Vue3 CDN

I am currently working on a project using Vue3 CDN because the project environment cannot run npm. I have been trying to create a component with html+CDN, but when attempting to create a recursive component, it only renders the top-level element. Is there ...

What is the best way to ensure that every item on a list can be

Is there a way to make both the left and right sides of a list item clickable? Currently, only the right side is clickable in my case. Any suggestions? This is my HTML: <body> <aside id = "aside"> <div id="column"> ...

Prevent the button from being enabled until the file input is updated

I want to create a form with an input file for uploading photos, but I need the submit button to be disabled until the input file has a value. Additionally, there are other validations that will also disable the button. Here is the structure of my HTML fi ...

How about this: "Is it possible for the accordion to open when clicked and show

Screenshot illustrating the issue I need assistance with implementing a hover preview for the contents of the accordion, followed by keeping it open upon clicking. The codepen link is provided below for reference: Visit the codepen here <script src=&q ...

Conceal Content from Onsite Search

Is it possible to conceal text from on-page browser searches (e.g. Ctrl+F) in a dependable manner while keeping it visible? I thought that adding aria-hidden="true" would address the issue, but the text remains searchable by browsers. ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...