Modify the div's width from 100% to 1000 pixels when it is less than 1000 pixels, using Javascript

I need help with writing Javascript code that will change the width of a div element called "red" from 100% to 1000px when the browser width is less than 1000px. The code should revert the width back to 100% when the browser width is greater than 1000px. I am focused on learning pure Javascript without relying on JQuery. I have found many JQuery solutions, but I want to master Javascript first. The reason I want to change the "red" div element is because min-width: 1000px; is not supported in Internet Explorer. Any assistance or guidance on this matter is greatly appreciated. Please check out this JSFiddle link for reference.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>

<head>
<title>Positioning</title>

<style type="text/css"> 
#red {position: absolute; margin-top: 100px; width: 100%; min-width: 1000px; height: 400px; background-color: red;} 
#contents {position: relative; top: 10px; width: 1000px; height: 600px; margin: 0px auto; border: 1px solid white;} 
html, body, div {margin: 0; padding: 0; border: 0;}
</style>

</head>

<body style="background-color: black;">

<div id="red"></div>
<div id="contents"></div>
</body>

</html>

Answer №1

Here is a JavaScript code snippet that adjusts the width of an element based on the viewport size:

window.onresize = function() {
    var widthViewport = window.innerWidth || document.body.clientWidth;
    var el = document.getElementById('red');

    if( widthViewport < 1000 ) {
        // Append the classname which specifies the fixed width
        el.className += ' fixed_width';
    } else {
        // Remove the classname that fixes the width at 1000px
        el.className = el.className.replace( /(\b\s*fixed_width\b)+/, '' );
    }
};

And here is the corresponding CSS code:

.fixed_width{
    width: 1000px;
}

Answer №2

Give this a shot


document.addEventListener('DOMContentLoaded', function() {
    var screenWidth = document.body.clientWidth;
    if(screenWidth < 1200) {
        document.getElementById('blue').style.width = '1200px';
    }
});

Answer №3

let redElement=document.getElementById('red');  

/** Detecting the browser width **/
let windowWidth=window.innerWidth || document.body.clientWidth; 

if(windowWidth<1000) 
{
    redElement.style.width='1000px';
}
else
{
    redElement.style.width='100%';
}

Answer №4

To support older versions of Internet Explorer, you have a few options for incorporating JavaScript. You can include it in the header, an external file, or use the expression property in CSS.

The expression property allows you to add JavaScript code inside a CSS file that will only be recognized by IE.

Here is a basic example:

 = document.body.clientWidth < 1001 ? "100px" : "auto"

In your CSS file, you can use the following code:

width: expression( document.body.clientWidth < 1001 ? "100px" : "auto" ); /* set min-width for IE */

Answer №5

Is this what you're looking for? http://jsfiddle.net/ghPqM/2/ ?

checkWindowSize();
window.onresize = checkWindowSize;

function checkWindowSize(){
    var blueElement = document.getElementById("blue");
    var windowWidth = window.innerWidth;

    if (windowWidth < 1200){
        blueElement.innerHTML = "Under 1200 pixels";
    } else {
        blueElement.innerHTML = "Over 1200 pixels";
    }
}

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

Encountering an ENOENT error while attempting to incorporate a style guide into next.js (react)

Recently, I delved into learning next.js and decided to enhance my project with documentation using To kickstart my project, I utilized npx create-next-app After installation and configuration setup, I added the following code snippet: [styleguide.config ...

Sluggish Bootstrap Carousel Requires Mouseover or Click to Start Sliding

Having Trouble with Bootstrap Carousel Sliding: I've been trying to solve this issue for a while now, but nothing seems to be working. I know this might be a common question, but I really need to fix this problem quickly and none of the suggested solu ...

Prevent the reloading of the page by utilizing Ajax technology when submitting a form in Laravel

I'm facing a challenge with processing a form submit using ajax instead of Laravel to prevent page reloads. Unfortunately, it's not working as expected and I'm struggling to figure out the issue. Despite researching numerous examples online, ...

What is the method for displaying script commands within package.json files?

With a multitude of repositories, each one unique in its setup, I find myself constantly referencing the package.json file to double-check the scripts. "scripts": { "start": "npm run dev" "build:dev": "N ...

Discover a foolproof method for effortlessly examining an flv or mp4 file embedded within a webpage simply by

I've encountered a challenge with JavaScript. I can successfully check a flash object in a webpage when hovering over it, but I'm unsure how to achieve the same for flv or mp4 objects when either hovering over or moving away from them. Currently ...

Having trouble retrieving data from the PokeAPI

Currently, I am experimenting with PokeAPI for educational purposes and attempting to run the following code: const express = require('express') const https = require('https') const app = express() const port = 3000 app.get('/&apo ...

Using the Set function to compare distinct elements within different arrays

Update: After reviewing the link shared by faintsignal, it appears to be the most suitable answer. It not only clarifies why this behavior is happening but also provides a solution to the issue at hand. I am currently working with an array and trying to d ...

The vertical drop-down menu is displaying and functioning incorrectly

My vertical submenu is positioned correctly, but the links are overlapping on top of each other. The submenu doesn't hide when hovering over the main menu, but it does hide when hovering outside the menu. I'm unsure of what changes or additions t ...

extracting an empty value from this variable

When I click on an anchor tag using this operator, the value appears blank. I have multiple divs with the same class, so I used the .each() function, but I can't figure out where I'm going wrong. The desired output is that when I click on one of ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Ways to display multiple PHP pages in a single division

Within my project, I have a unique setup involving three distinct PHP pages. The first file contains two divisions - one for hyperlinked URLs and the other for displaying the output of the clicked URL. Here is an excerpt from the code snippet: <script& ...

When setting the margin to auto, it perfectly centers elements on servers and IE, but on Chrome off the server, it appears to be aligned to the

There seems to be an issue with the display of my page in Chrome - it starts at the middle and ends on the right side. However, when I view it on my server or try it on Internet Explorer 11, it appears centered. Why is that? This problem only arose after ...

$rootScope undefined in an easy AngularJs Routing Demo

I've been trying to access the name and age using $scope and $rootScope, but I keep getting an error even though I'm pretty sure everything is set up correctly. Can someone please point out where I might be making a mistake? <html> <he ...

What is the method for customizing the background color in a .vue file using Bootstrap?

Can anyone assist me in updating the background color of a div class from grey to white? The code is within a .vue file using Bootstrap and includes an enclosed SVG file. Here's the snippet: <div class="text-left my-3 bg-white"> <button var ...

Removing an item from a React (Hooks) array state: A step-by-step guide

In my code, I have a list of text inputs populated from an array and I am trying to delete a specific element based on its index. The issue I am facing is that even though the console log correctly shows the updated array without the removed element, visua ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

Next JS restricts XLSX to return only 100 objects as an array of arrays

I've developed a file upload system that reads Excel files and uploads data to a database (using Mongoose). After implementing the code, I noticed that when I use console.log(sheetData), it returns an array of arrays with objects inside. Each internal ...

Tips for toggling the visibility of a revolution slider based on current time using JavaScript

Currently, I am integrating the revolution slider into my WordPress website. My goal is to have the slider change according to the standard time of day. For instance, I want slider1 to display in the morning, slider2 at noon, slider3 in the evening, and sl ...