Changing the appearance of a website by applying various stylesheets based on the size of the browser window in

After implementing the code below to switch between stylesheets based on browser height, I encountered a small issue. The code works perfectly when the page first loads or when the window is resized and then refreshed. However, I'm curious if there's a way to adjust the code so that it dynamically selects the correct stylesheet as the window is being resized.

if (window.innerHeight <= 900) {
    loadcss('css/container_sm.css');
} else {
    loadcss('css/container_lg.css');
}

function loadcss(file) {
    var el = document.createElement('link');
    el.setAttribute('rel', 'stylesheet');
    el.setAttribute('type', 'text/css');
    el.setAttribute('href', file);
    document.getElementsByTagName('head')[0].appendChild(el);
}

Answer №1

Instead of reinventing the wheel, you may want to explore utilizing a pre-existing library like twitter bootstrap. This library offers responsive stylesheets that automatically adjust when the window is resized.

Answer №2

If you want to incorporate event handling into your script, consider using jQuery

$(window).resize(function(){
   if (window.innerHeight <= 900) {
    loadcss('css/container_sm.css');
   } else {
    loadcss('css/container_lg.css');
   }

})

Alternatively, without using jQuery:

window.onresize = function(){}

Answer №3

Give this a shot:

document.body.onresize = function (){
    if (window.innerHeight <= 900) {
        applyStyles('css/container_sm.css');
    } else {
        applyStyles('css/container_lg.css');
    }
};

Answer №4

Our task at hand involves the following steps:

  1. Upon resizing of the browser, we need to verify if the change in height has transitioned from small (<= 900px) to large (> 900px), or vice versa. If this specific condition isn't met, like in the case where the user resizes from 600px to 601px only, there is no necessity to update the CSS.
  2. Whenever we observe a switch in browser size from small to large, or vice versa, we meticulously choose and eliminate the old container_lg.css or container_sm.css.
  3. Subsequently, the appropriate CSS is added.

Below is the corresponding code snippet:

var SMALL = 0;
var BIG = 1;
var previousSize = null;
var thresholdHeight = 400;
var firstCall = true;

function selectCSS()
{
    if ((previousSize == null || previousSize == BIG) &&
         window.innerHeight <= thresholdHeight) {

        removeOldCSS();
        loadNewCSS('css/container_sm.css');
        previousSize = SMALL;

    } else if ((previousSize == null || previousSize == SMALL) &&
                window.innerHeight > thresholdHeight) {

        removeOldCSS();
        loadNewCSS('css/container_lg.css');
        previousSize = BIG;
    }
}

function removeOldCSS(file)
{
    var headNode = document.getElementsByTagName('head')[0];
    var linkNodes = document.getElementsByTagName('link');
    for (var i = 0; i < linkNodes.length; i++) {
        var linkNode = linkNodes[i];
        if (linkNode.parentNode == headNode &&
            linkNode.href.search(/css\/container_(?:sm|lg).css$/) >= 0) {

            headNode.removeChild(linkNode);
        }
    }
}

function loadNewCSS(file)
{
    var el = document.createElement('link');
    el.setAttribute('rel', 'stylesheet');
    el.setAttribute('type', 'text/css');
    el.setAttribute('href', file);
    document.getElementsByTagName('head')[0].appendChild(el);
}

window.onload = selectCSS;
window.onresize = selectCSS;

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

Angular material is experiencing an issue where content is being cut off or

I am currently working on a project using AngularJS for a web application. I have encountered an issue where some of the content in the md-content element is being clipped. For instance, the body tag has the style: overflow: hidden, and the child md-conte ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

Why am I unable to locate my personalized module?

I've encountered an issue with my npm module not being found in my sample script after publishing it. Here is the link to my module: https://www.npmjs.com/package/kong-hmac https://github.com/y-zono/kong-hmac-js Here's what I have tried: $ m ...

When attempting to import * as firebase from 'firebase/app', the result is null

Recently, I've been encountering an issue while attempting to incorporate firebase v9 into my Next.js project. Every time I import it, it returns as undefined... import * as firebase from 'firebase/app' export function getFirebaseApp() { ...

Using SOAP in a JavaScript-exclusive setting

I'm looking into utilizing SOAP as the backend services to supply data for my application. My query pertains to the feasibility of implementing this with just a JavaScript framework like Ember or Angular, without utilizing server-side languages such ...

Exchange data using socket.io in nodejs and express with a different javascript file

Imagine having a JavaScript file that needs to interact with another JavaScript file in order to share data between them. For instance, let's consider a file named game_server.js. Within this file, there are two variables that we want to access in th ...

IE's inconsistent float alignment causing display issues

My challenge is getting my div elements to float correctly in Internet Explorer. They are displaying perfectly in Chrome and Firefox, but IE seems to be messing up the code. The jsfiddle link showcasing the issue can be found here: http://jsfiddle.net/vlya ...

When writing CSS, ensure there is no space between selectors and classes of elements

Can you explain the distinction between using a css selector (like p) and assigning a class to an element (.cat)? p.cat{ } Vs. p .cat{ } Appreciate your help! ...

Looking for guidance on implementing throttle with the .hover() function in jQuery?

Seeking a way to efficiently throttle a hover function using jQuery. Despite various examples, none seem to work as intended. The use of $.throttle doesn't throw errors but ends up halting the animation completely. Here is the code snippet in question ...

Eliminate an item from a JavaScript array

I am trying to remove a specific element from a JavaScript array. The element I need to remove is the one with the value of 'NT'. In my HTML input, I have: <input type="text" id="caseType" size="50"/> To populate it, I use: var c ...

Is there a way to transform NextJS typescript files into an intermediate machine-readable format without having to build the entire project?

I need to deliver a Next.js project to my client, but I want to modify the TypeScript files so they are not easily readable by humans. The client will then build and deploy these files to their production environment. How can I achieve this? In summary, C ...

Storing the options' ids in an array within a select box using JavaScript: tips and tricks

Check out this snippet of HTML code: <select id="s1"> <option value="volvo" id="o1">Volvo</option> <option value="saab" id="o2">Saab</option> <option value="opel" id="o3">Opel</option> <option value="au ...

Avoiding interference with adjacent elements caused by long content in a div

Hey there, I could really use some help with my CSS layout, I'm pretty new to CSS and Flexbox and I'm trying to create a simple layout. The issue I'm running into is how to stop long content inside a pre tag from pushing other divs. Here& ...

Triggering a specific outcome with every user interaction involving the selection of an element

How can I trigger this effect each time the user clicks on the element using jQuery? I have added a "ripple" class upon clicking, but when I click on the element for the second time, the effect does not execute because the class has already been added. Ho ...

Trouble displaying background image in Electron Application

When I try to load an image file in the same directory as my login.vue component (where the following code is located), it won't display: <div background="benjamin-child-17946.jpg" class="login" style="height:100%;"> A 404 error is popping up: ...

Utilizing AJAX and PHP to refresh information in the database

For my project, I need to change the data in my database's tinyint column to 1 if a checkbox is selected and 0 if it is deselected. This is the Javascript/Ajax code I have written: <script> function updateDatabaseWithCheckboxValue(chk,address) ...

How to fetch JSON data from a URL in Angular 2

let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let ep = './data.json'; this.events = this.http .get(ep, { headers: headers }) .map(res => res.json()) .map(({results}: ...

Is it possible to remove an element from a data structure in a web application using an HTTP command?

Apologies for the confusing title, I struggled to find a better way to describe it. Imagine sending a GET request to an API and receiving this data: { {id: 1, name: "John Doe", tags: ["Apple", "Orange", "Pear"]}, {id: 2, name: "Jane Doe", tags: [ ...

Having difficulty aligning block element in the center horizontally

I am struggling with centering elements for a list of upcoming blog posts. The Postlist component is integrated into my App.js file. Although I successfully centered the navigation bar following the method described here in the Horizontally section and spe ...

The contents of a JSON Object will not be logged by Node, no matter the approach

I am currently encoding data for a Node.js WebSocket server in JSON format. When attempting to display the contents of the JSON object on the server side, I am encountering the issue where Node simply logs object Object I have experimented with the follow ...