My jQuery function only activates when I manually adjust my window size to mobile, but doesn't work when I refresh the

I'm currently working on a code snippet to dynamically add and remove classes on mobile devices. It seems to function properly when I manually resize the browser window to mimic a mobile screen, but upon refreshing the page, it stops working.

$(document).ready(function(){
 $(window).on('load, resize', function mobileViewUpdate() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
        $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
        $('#nav-icon').addClass('navbar-toggler-icon2');
    }
  });
});

Answer №1

Although I concur with the previous response recommending extracting the logic to a method and utilizing it in multiple places (to avoid passing logic through the DOM), you still have the option to fire the event on ready if desired.

$(document).ready(function(){
  $(window).on('load, resize', function mobileViewUpdate() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
         $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
     $('#nav-icon').addClass('navbar-toggler-icon2');
    }
  }).trigger('resize');
});

Answer №2

Consider refactoring the mobileViewUpdate function:

function updateMobileView() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
         $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
     $('#nav-icon').addClass('navbar-toggler-icon2');
    }
}

Next, ensure to call it within both document.ready and on resize:

$(document).ready(function(){
 $(window).on('resize', updateMobileView);
 updateMobileView();
});

This approach should address the issue. Nonetheless, employing meta viewport tag and media queries might offer a more robust solution for optimizing the website for mobile devices.

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

Implementing Enter key functionality to add items to a Todo list using pure DOM manipulation

var listLis=document.getElementById('list'); const addbutton=document.querySelector('.fa-plus') const inputBar=document.querySelector('.show') function showInput(e){ inputBar.classList.toggle('show') } addbutt ...

Center the image within the navbar container

<nav class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-to ...

Seeking assistance to transfer div elements into a different div post an onclick event

I have a container that contains four separate divs. My goal is to append the remaining three divs to another specific div after clicking on one of them. Does anyone know how I can achieve this? <!DOCTYPE html> <html lang="en"> < ...

Obtain a collection of chosen dates from the availability scheduler

I am currently working on an availability calendar where users can select multiple dates. While I have successfully been able to retrieve the value of each individual cell, I am facing difficulty in getting an array of values for all the cells selected. ...

Using HTML button to trigger external javascript functions

I am facing an issue while setting up a page to execute an external Javascript function when the user clicks a button in an HTML form. The function named lock() is not being called correctly, and my button code looks like this: <form> <button typ ...

Can the appearance of the Chrome browser be altered to resemble a printed page?

Simply put, I'm tackling a massive project right now. While my print.css is functioning perfectly, the task of constantly previewing the print page has become incredibly frustrating. What's more, it's impossible to inspect the page effectiv ...

Is the execCommand('copy') function ineffective within an Ajax or XHR callback?

(Tested on Chrome 44) Intended outcome: Perform XHR request, display result in text area, automatically select text, and copy it to clipboard. Current behavior: Despite successfully fetching the result and selecting it in the text area, the copying proce ...

A TypeError was encountered: Attempting to read the 'substr' property of an undefined variable

Recently, I encountered an issue while working on a script with jquery.min.js version 1.4. The problem arose when I had to upgrade the script to version 1.9.1. Uncaught TypeError: Can not read property 'substr' of undefined. I need assistance i ...

Tips for customizing a user's profile view using Django

I am currently designing a form that allows users to update their profile information. I have created two separate forms for this purpose - one for editing the User model (first_name, Username, and Email) and another for the Profile model (biography). The ...

Issue with CSS floating elements on left or right causing a significant gap

I've encountered an issue with my CSS layout. I have specified "float:right; clear:right" for ads and "float:left" for blocks in the main text meant to flow like images. However, there is a significant gap in the main text flowbox. The main text only ...

Sending data from an AJAX POST request to a Grails Controller

Currently, I am in the process of developing a social networking platform using Grails. However, I have encountered a roadblock when it comes to allowing users on their edit profile page to input a YouTube URL into a text field. By clicking a button, a Jav ...

A guide on retrieving values from programmatically created input elements in Java

Here's the HTML code that I am currently working with: <form method="get" action="#" id="startForm"> <input type="text" name="period" id="period" placeholder="The number of days"/> <input type="submit" name="submit" value="subm ...

Ensure that your Bootstrap columns span across the entire width of the row

I'm new to bootstrap and struggling with a simple issue. I want the columns to fill 100% of the width of the row, but I can't figure out how to remove the padding while maintaining the spacing between them. Despite searching for a solution, I ha ...

Learn how to verify the existence of a URL or webpage using AJAX or jQuery

When a user is creating a profile, they have the option to include links to their websites or blogs that will be displayed on their profile page. Before saving these links to the database, I would like to verify if the provided URL exists. Is there a meth ...

Styling the select dropdown border in Google Chrome

I am encountering an issue with styling HTML select options in Chrome. Despite successfully applying borders to each option in Firefox, I cannot get it to work in Chrome. Can anyone advise on how this can be achieved? <select id="sortingOptions" class= ...

Troubleshooting a problem with jQuery child items

Could someone help me understand why the second div is affected by the last part of the code and not the first? It's puzzling to see all the content disappear, especially when I expected the first div to be impacted as it seems like the immediate pare ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

Sibling div positioned below the main div

I have a container div with two child divs inside. The first child div has a fixed width, but its height depends on the content (a message box). Right next to it on the same line, I want another div (displaying the time) to be at the bottom of the parent d ...

Jquery code malfunctioning on Django paginated webpages

I've tried countless things and searched high and low, but nothing has seemed to resolve my issue. Issue: I have a jQuery script that functions perfectly on the initial page, but fails to run on subsequent paginated pages. I encountered a similar pro ...

Deactivate the current session by choosing an item from the drop-down menu

I'm looking to incorporate an option in my dropdown menu that unsets or destroys the session $_SESSION['selected_opt]. Sample code: <form class="search-form"> <select name="thema" class="selectpicker"> <option value=" ...