Modify the background of a div according to the size of the screen. Implement this functionality using JavaScript and

After reviewing a specific post at , I find myself unsure of how to target a particular class for reference.

I am certain that I want to implement

document.onload = checkWidth();

window.onresize = checkWidth();

However, I am uncertain about the procedure to change the background of a div based on the screen size of the device or the current browser window size. Here is my current setup, with Bootstrap being used for CSS

<div class="row">
 <div class="col-sm-6 background1 border-design">
  <p>Placeholder</p>
 </div>
</div>

regarding CSS

.background1 {
 background: linear-gradient(100deg, #87CEFA 0%, #FF8C00 100%);
}
.background2 {
  background: linear-gradient(100deg, #FF8C00 0%, #C0C0C0 100%);
}

Suppose I want the background to switch to .background1 when the browser window size is ≥576px (due to using col-sm-6), but switch to a different style, like .background2, when the browser window size is less than or equal to 576px.

Answer №1

The class property named classList contains the classes assigned to a specific DOM element. These classes can be manipulated based on the screen size requirements.

Below is one suggested way to implement this:

<div class="row">
 <div id="to-change" class="col-sm-6 background1 border-design">
  <p>Content Placeholder</p>
 </div>
</div>

For the JavaScript part, the code could be:

window.onresize.apply(updateBackground);

function updateBackground(){
    let window_width = window.innerWidth;
    if (window_width >= 576) document.getElementById("to-change").classList.remove("background1").add("background2");
    else document.getElementById("to-change").classList.remove("background2").add("background1");
}

Answer №2

1) The function checkWidth does not need to be called explicitly, as JS will automatically call it when needed. Just pass the reference to it.

2) To add or remove a class on an HTML element, you can use either the add or remove method of the classList.

container.classList.remove("background1");
container.classList.add("background2");

const container = document.querySelector(".bg-container");

function checkWidth() {
  if (window.innerWidth < 600) {
    container.classList.remove("background1");
    container.classList.add("background2");
  } else {
    container.classList.add("background1");
    container.classList.remove("background2");
  }
}

document.onload = checkWidth;
window.onresize = checkWidth;
.background1 {
  background: linear-gradient(100deg, #87CEFA 0%, #FF8C00 100%);
}

.background2 {
  background: linear-gradient(100deg, #FF8C00 0%, #C0C0C0 100%);
}

.bg-container {
  padding: 1.5rem;
}
<div class="row">
  <div class="bg-container col-sm-6 background1 border-design">
    <p>Placeholder</p>
  </div>
</div>

Answer №3

You can achieve this with pure CSS

    .background1{
    background-color: red;
    }
    @media screen and (max-width: 768px)
    {
     .background1
     {
       background-color: green;
       color:white;
     }
    }
<div class="row">
 <div id="to-modify" class="col-sm-6 background1 border-design">
  <p>Placeholder</p>
 </div>
</div>

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

Bring life to the process of adding and removing DOM elements through animation

I am seeking to provide an engaging and interactive experience for my users while ensuring responsiveness. To achieve this goal, I have decided to learn more about web development by creating a card game. My current setup involves clickable elements that ...

I am having issues with my bootstrap navigation pills, they seem to be malfunctioning

Having some issues setting up a bootstrap pill nav menu. The pills aren't working properly and all content appears on one page, despite the active pill changing. <div class="navigation"> <ul class="nav nav-pills head-menu" id="n ...

Tips for maintaining consistent styles in CSS for multiple websites

I am currently working on developing a customizable chatbot widget using react. The goal is to create a chatbot widget that can be easily integrated into any website, similar to the functionality of rasa-webchat. During testing on some websites, I encount ...

How to Upload Your Avatar Image with the Stream-Chat API from GetStream.io

I am currently in the process of developing a Stream-Chat API project and I want to allow users to upload images directly from their devices. Upon testing, everything seems to be working fine, but the uploaded image is not displayed - only the default avat ...

Excessive Font Awesome Icons causing navigation bar to appear oversized

My Font Awesome icons are causing my navbar to expand in height. Despite resetting all margin and padding to 0, adjusting the margins and paddings of the icons has not helped. I even tried setting negative top and bottom margins/paddings. https://i.sstati ...

Show the profile picture of a model in a Django template

I am trying to display the user's image by inserting it into the src attribute of the img tag, but I am facing difficulties with it. Here is my code: models.py class allusers(models.Model): user = models.OneToOneField(User, on_delete=models.CASC ...

`Scrolling through a horizontal menu with no scrollbar present`

Is there a way to create a horizontal menu that can scroll left or right without the scrollbar? I'm looking for a solution like adding on-screen arrow buttons or implementing mouseover functionality. What would be the best approach? div.scrollmenu ...

Utilizing CSS Grid to dynamically stretch and wrap rows based on adjacent siblings within a flat DOM structure

Looking for a way to create a grid layout that adjusts row sizes based on adjacent siblings. Interested in SCSS or CSS solutions using grid, flexbox, or other techniques. https://i.sstatic.net/Ump5U.png I am working with a dynamically generated list base ...

Is it possible to prevent the fade out of the image when hovering over the text after hovering over the div or image, causing the text to fade in?

Using React and CSS. I have set up my application to display a faded image on hover, with text that fades in over it. However, I am facing an issue where touching the text with my cursor removes the fade effect. Does anyone have a solution for preventing ...

Dismiss Bootstrap by clicking anywhere

I have a specific input that is displayed when clicked and disappears with the next click: <a href="#;" class="asset_info" data-asset_id="{{ asset.pk }}" data-toggle="focus" tabindex="0" data-placement="left" data-trigger="focus" >Hello</a> ...

Error alert: $.simpleWeather function not found

Currently, I am attempting to incorporate simpleWeather.js from the website simpleweatherjs.com into my own website. However, upon inserting the html code onto my website, an error message pops up: Uncaught TypeError: $.simpleWeather is not a function ...

Tips for looping through the new element that has been added to an array from the database query result

I am faced with a challenge involving querying a mysql database using each element of an array in Node.js. If a specific condition is met, I need to append additional elements to the same array and iterate through them as well. As I am new to Node.js, I a ...

Generate an array consisting of characters within a designated range

I recently came across some Ruby code that caught my attention: puts ('A'..'Z').to_a.join(',') The output was: A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z I'm curious if there is a similar way to achieve this ...

Retrieve the count of ng-if directives that match a specific ng-repeat content

Imagine a scenario where HTML code looks like this: <md-grid-tile class="gray" ng-repeat="carto in cartoList" ng-if="search(carto)"> <md-button ng-click="changeSVG(carto.fileName)" aria-label="carto.displayName"> <img ...

There is an issue with the functionality of Java code that has been adapted from Javascript logic

I'm currently using NetBeans8 IDE. Check out this java script function from this Fiddle function animate() { xnow = parseInt(item.style.left); item.style.left = (xnow+1)+'px'; ynow = parseInt(item.style.top); item.style. ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

Can I initiate an AJAX call from a different JSP page?

My scenario involves a JSP page that opens another JSP in a new tab. In the second JSP, I upload a file to the server, as I have certain important operations to perform there. However, I also need to include a link to this uploaded file in the first JSP ...

If a radio button is either selected or deselected, a jQuery alert will display the value of the radio button

When a user logs into the system, there is a radio button that is almost checked. I want to create an alert when the user clicks the button to show whether it is checked or unchecked. This is the HTML code for the radio button: <input id="radio1" name= ...

The navigation bar text spills over the designated area

I'm facing an issue in the front end where the navbar does not adjust on narrow screens, causing text to overflow. Although it works fine on wide monitors and mobile screens, iPads in portrait view have the last section of the navbar extend outside of ...

What are the best practices for utilizing pre-defined CSS classes in Vue.js libraries?

I don't have much experience with CSS, but I'm really eager to customize the appearance of my chart. The chart is generated by a vue.js library and comes with pre-defined CSS classes. However, I'm uncertain about how to access and modify the ...