"Implementing class changes based on screen size using javascript is not functioning as expected

var d = document.getElementById('promo5');

var viewportWidth = window.innerWidth;


function mobileViewUpdate() {

    if (viewportWidth <= 700) {
        d.className += (" .promo5-mobile");
    } else if (viewportWidth >= 700) {
        d.className += ("");
    }
}


window.onload = mobileViewUpdate();
window.onresize = mobileViewUpdate();

Add a class to the div below:

<div id="promo5" class="promo5">

This will enable it to display on the mobile version of my website.

.promo5-mobile {
    display: none;
}

I am facing an issue where the class is not being added, even though it works when I run it in my browser console. I have verified that my JavaScript file is functioning correctly. As a beginner, I suspect it may be something simple that I am missing.

UPDATE: I corrected the improperly worded if statement to else if, moved the viewportWidth variable inside the function, and checked with the browser inspector, yet the class is still not being added. If no solution is found, I plan to resort to using media queries instead.

Answer №1

Alright, there are several errors that need fixing:

  1. Make sure to move

    var viewportWidth = window.innerWidth;
    inside the mobileViewUpdate function to ensure its value is updated whenever needed.

  2. When calling the function on resize, use

    window.onresize = mobileViewUpdate
    without brackets.

  3. Correct the condition statement - remove brackets after else.

  4. Avoid adding promo5-mobile to the className every time you resize a small window; also remember to remove this class when resizing back to medium or large.

Here is how it should be fixed:

var d = document.getElementById('promo5');

function mobileViewUpdate() {
    var viewportWidth = window.innerWidth;
    if ( viewportWidth <= 700 ) {
        if ( d.className.indexOf(" promo5-mobile") === -1 ) {
            d.className += (" promo5-mobile");
        }
    } else {
        if ( d.className.indexOf(" promo5-mobile") > -1 ) {
            d.className = d.className.replace(" promo5-mobile", "");
        }
    }
}

window.onload = mobileViewUpdate;
window.onresize = mobileViewUpdate;

Answer №2

The reason it's not functioning correctly is due to an error in your if/else statement. Instead of using else, consider using else if, or you can simply use the else statement without specifying (viewportWidth >= 700). Please refer to the updated code below:

Revision 1: Implement the classlist method instead of className to enable your JavaScript to add a class. Refer to the following snippet:

function mobileViewUpdate() {
    if (viewportWidth <= 700) {
        d.classList.add("promo5-mobile");
    } else {
        d.classList.remove("promo5-mobile");
    }
}

Answer №3

Make sure to include a space instead of a dot in the class name. For example, if you are using .promo5-mobile in your CSS file, your JavaScript code should be

d.className += (" promo5-mobile");
, without the dot.

Note: It's important to note that as mentioned by Nikolay, the variable viewportWidth is only being set on page load. If the function is called on window resize, make sure to update the viewportWidth to reflect the current width for accurate results.

Additional Tip: Consider utilizing CSS @media queries to hide elements based on screen size rather than solely relying on JavaScript. Here's an example of how you can do it in your main CSS file:

#promo5 {
  display: none;
}

@media (min-width: 700px) {
  #promo5 {
    display: block;
  }
}

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

Arranging DataTable by the newest date

I need to change the default sorting of a table from old date to recent date (1st column). Here is the code I have been trying: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"cle ...

JavaScript: Transform a JSON string post-callback into a plain JavaScript array

After successfully creating a PHP function to check for array duplicates, I am now faced with the task of converting the returned JSON string into a pure JavaScript array. Assuming there are no duplicates in the array, of course. Below is the code from my ...

Unable to submit any data through the form in Sails.js

Lately, I encountered an unusual issue when trying to submit a form. Everything functions properly when there is no attachment or the size of the attached image file is under 100kb. However, as soon as I attempt to upload a file larger than 100kb, none of ...

The jQuery validation code is functioning properly, yet it is resulting in the same files being uploaded to both separate folders

Below is the query code I am using, and it seems to be working well: $("#formAbout").validate({ ignore:[], errorPlacement: function (error, element) { var lastError = $(element).data('lastError'), ...

Issue with Chrome on android causing local website javascript and css to not load properly

The issue I am experiencing is unique to Chrome for Android when accessing a local website. Interestingly, the site functions perfectly on Firefox for Android but encounters problems on Chrome. Specifically, on my website , there is a download link for a ...

implementing a calendar picker within a linked select dropdown using ajax

I'm currently working on fixing multiple errors, but one question that I have is why the datepicker doesn't pop up when I click on it. Which div should I be targeting for this functionality? <?php require '../common/pdo_connect.php' ...

The format for establishing an array with a specific key

Edit: simplifying further. Take a look at this code snippet: let arr = [42,69] arr.key = 'lol' This code adds a key value to an array. Is there a way to combine these two lines into one? I've been trying different syntax but nothing seems ...

Utilizing a factory as the data source in angular-datatables leads to unexpected errors

Is it possible to use a factory as a source data in angular-datatables? Basically, I want to retrieve data in a variable and use it as the data source. UPDATED (06/22/2016) This is my updated factory: statisticsModule.factory('globalFactory&apos ...

Discover the ultimate guide to maintaining individual premium memberships in a Next.js application using the powerful combination of Redux, Firebase, and Stripe. Never worry about users losing their premium status again after

I have integrated Stripe for users to purchase premium subscriptions, but I am facing an issue with storing their premium status in Redux Persist State. After they log out, the state refreshes and upon logging back in, they are required to purchase a premi ...

Tips for preventing tiny separation lines from appearing above and below unordered list elements

I am attempting to utilize twitter bootstrap to create a select-option style list. How can I eliminate the thin separation lines above and below the list of items? Refer to the screenshot: https://i.sstatic.net/1khEE.png Below is the visible code snippe ...

Is there a way to determine if any word within a given text is present in an array?

Imagine you have the following full text: var nation = "Piazza delle Medaglie d'Oro 40121 Bologna Italy" And a given array like: ["Afghanistan", "Italy", "Albania", "United Arab Emirates"] How can we verify if the exact word Italy within that ent ...

Is it possible to create a "private" variable by utilizing prototype in JavaScript?

In my JavaScript code, I am trying to have a unique private variable for each "instance," but it seems that both instances end up using the same private variable. func = function(myName) { this.name = myName secret = myName func.prototype.tel ...

The function "Jest spyOn" does not exist

I’m currently facing an unfamiliar error while testing my React component using Jest. Here’s the code snippet for my <Row/> component: In my Row component, there are various methods like showDetailsPanel(), handleStatusChange(), handleModalCanc ...

The php code managed to infect my website

My website has been infected by a plugin that is generating ads for a company I am not affiliated with. I tried using anti-malware software, but it didn't detect anything. var doc = document.getElementById('ad_iframe').contentWindow.document ...

Obtain data from ng-model in AngularJS $scope

I am using the angularjs framework to create a form.html and a controller.js. In the controller, I have a variable that retrieves the SSID of a box. My question is, how can I automatically assign the value of this variable in the input field of the form? I ...

What is the best way to convert a string to an object?

I wrote this code snippet: var regex={"$regex":req.query.query,"$options":req.query.options } db.collection('coders', function(err, collection) { collection.find( {"name":regex} ).toArray(function(err, items) { res.send(item ...

Error loading the app.html file

Whenever I include templateUrl in the @Component section, an error pops up in the browser console. @Component({ selector: 'http-app', directives: [ ], templateUrl: "app.html", }) class HttpApp { } Error: Uncaught (in promise): Failed t ...

Creating a custom scrollbar within a div using CSS and JavaScript

In my final school project, I have implemented a custom scrollbar with divs that have a border radius of 15px. However, when I add the custom scrollbar with the same border radius, it overlaps the div and does not look as visually appealing as I would like ...

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

What do you think of the unique JSON syntax found in the React-Redux-Firebase documentation? Valid or not?

The React-Redux-Firebase documentation showcases a sample code snippet. import { compose } from 'redux' import { connect } from 'react-redux' import { firebaseConnect, populate } from 'react-redux-firebase' const populates = ...