Implementing a jQuery function to trigger window resize on window load

I'm facing an issue with my resize function where the contents within a window change when it reaches a certain width. I'm trying to achieve this same effect on window load but haven't been successful so far. Here's what I've attempted:

Attempt 1

$(window).load(function () {
       updateDivsMargins();

        $(window).resize(updateDivsMargins);

        function updateDivsMargins() {
                var windowWidth = $(window).width();
                if (windowWidth >= 2560) {
                    alert("hello im 2560")
                    $('.1').css('margin-left', '500px');
                    $('#2').css('margin-right', '-300px');
                    $('#3').css('margin-left', '550px');
                    $('#4').css('margin-right', '-28em');
                }

        }

    });

Attempt 2

$(window).on("resize", function () {
            var windowWidth = $(window).width();
            if (windowWidth >= 2560) {
                alert("hello im 2560")
                $('.1').css('margin-left', '500px');
                $('#2').css('margin-right', '-300px');
                $('#3').css('margin-left', '550px');
                $('#4').css('margin-right', '-28em');
            }
        }).resize();

When I resize the page, the changes take effect as expected. However, if the page loads at exactly 2560, the changes are not applied. I'm wondering how I can make these changes apply both on load and resize. What am I missing in the two attempts above that is preventing them from taking effect on load?

Answer №1

It's a good practice to define your function outside of the event handler functions. I suggest using the following approach:

 $(window).resize(updateDivsMargins);
 $(document).ready(function() {
     updateDivsMargins();
 });

Alternatively, utilizing CSS media queries could be an even more effective solution based on the code provided.

Answer №2

When working with window events like load and resize, it's important to keep them separate instead of nesting one inside the other. You can define both event handlers separately but make them call the same function, as shown in the example below.

In simple terms, if the window width is greater than or equal to 2560 during the load or resize event, then the condition in the function updateDivsMargins() will be met.

$(window).load(function() {
  updateDivsMargins();
});

$(window).resize(function() {
  updateDivsMargins();
});


function updateDivsMargins() {
  var windowWidth = $(window).width();
  if (windowWidth >= 2560) {
    alert("hello im 2560")
    $('.1').css('margin-left', '500px');
    $('#2').css('margin-right', '-300px');
    $('#3').css('margin-left', '550px');
    $('#4').css('margin-right', '-28em');
	}

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Steps for creating a jQuery function that responds to changes in a text box value

Currently, I have a text box containing certain values and a submit button alongside a slider. When I click the submit button, the slider changes. However, I would like to achieve the functionality where instead of clicking the submit button, changing the ...

JavaScript double-click functionality is not operational on IE9 and IE11 browsers

My JavaScript code has an issue where single-click opens a link in a new tab and double-click opens a lightbox. This works perfectly in all browsers except for IE9 and IE11. In my initial code, both single-click and double-click function correctly. However ...

How can I troubleshoot the if/else statements in the following script using Jquery?

When the user is active, the message should say: work / first div. If the user is not active (if there is no data), the message should say: not work / second div. Any suggestions on how to fix this? *The users in the code are generic, no sensitive infor ...

Using jQuery to delete data asynchronously with AJAX technology

I am currently working on a cart page that shows items in a user's shopping cart using ASP while retrieving data from a table. One of the features I have implemented is the ability for users to delete an entry by clicking on an image. I have successfu ...

Notify the chat when a new record is added to the database

Alright, so here's the issue I'm facing. I created a chat application using PHP and MySQL, but I noticed that when I enter text, it doesn't update in the other window automatically. This led me to experiment with iframes, which I found much ...

What is the best way to determine the height of a DIV element set to "auto"?

When setting a fixed height on a div using jQuery, such as $('div').height(200);, the value of $('div').height() will always be 200. This remains true even if the content within the div exceeds that height and overflow is hidden. Is th ...

Struggling to incorporate a three-strike mechanism into my JavaScript game

I need to implement a feature where the user can make up to 2 mistakes before losing the game. Here's what I need to do: - Set up a global variable to keep track of the number of mistakes - Initialize this variable during the startGame function - M ...

Creating dynamic forms with JQuery and ReactJS

I have been tasked with creating a form-builder that will be integrated into an application. My role is to focus on designing the front-end using ReactJS. The client’s requirements are very similar to the features of the "jQuery Form-Builder," so I decid ...

Retrieve the identification of elements with dynamically generated ids

I've dynamically generated a set of elements using Handlebars, as shown below {{#floor as |room i|}} <div class="btn-group-toggle" data-toggle="buttons" > <label class="btn btn-secon ...

The words overlaid on the image spill out beyond its edges

I want to create a design where the text flows outside of the image and continues into another container. After some trial and error, I managed to achieve a layout where the text seamlessly extends beyond the image and into a separate section. Ideally, the ...

The backend error message isn't triggering an alert!

My current issue involves using jQuery to execute a .php file. Whenever an error occurs in the backend, I want to display an alert message with the error details. However, when intentionally submitting with an error, no alert pops up and it just proceeds t ...

Hover Effect for Bootstrap Gallery

I've created a hover effect for my gallery that is embedded in a Bootstrap Grid. Although the hover effect itself works fine, on some screen sizes, the overlay ends up covering the gallery images. Does anyone have any ideas, solutions, or hints to so ...

React fullpage.js causing z-index stacking problems

Take a look at the demo here: I'm having trouble getting the 'more info' modal to display above all other elements on the screen. Here's the desired stacking order, with the highest stacked element listed first: modal nav open header ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

using JavaScript to strip away content following .jpg

var lochash = "#http://www.thepresidiumschool.com/news_image/102%20NRD_7420.jpg&lg=1&slide=0"; I am looking to eliminate or modify the content that comes after .jpg. ...

Transforming the pen into a creative assortment of animated social media icons for top-notch production

My goal is to incorporate animated social media icons on my website using only CSS without any JavaScript. I came across a pen called "Yet Another Set of Animated Social Icons" that I'm attempting to modify. The issue at hand is that instead of the c ...

Loading a page via AJAX without triggering a reload of the entire website

I am experimenting with loading content from a different page using AJAX. The website I am currently testing on is dev.dog-company.com. Here's the code snippet that I have been working on: $('a[rel="load"]').click(function(){ //var sit ...

Discovering inner arrays within an outer array using the Plus function

Apologies if these questions seem basic in terms of JavaScript. Challenge 1. I am attempting to write code that can identify an inner array within an outer array, and the structure of the array looks something like this; var array = ['Bob', [ ...

Implementing a technique for activating a Bootstrap modal using a function

Hello, I am currently experimenting with integrating JQUERY functionality into React, and it truly feels like magic. After conducting extensive research, I am attempting to trigger the Bootstrap Modal using an external function. Here is a link to my code ...

Await the reply from Angular while using Selenium WebDriver

I am currently automating an Angular-based application using Selenium WebDriver (Java). After selecting an option from a dropdown in the Application Under Test (AUT), data is loaded onto the page through an AJAX call to a web service. However, there is no ...