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

Using Rails to render a partial with jQuery for a loop function

I am trying to include a partial multiple times in my view with different parameters. I have a search form that returns project data in JSON format using Ajax. Now, I want to use a jQuery function to get the project and display it in the view. $.ajax({ ...

Steps for linking a keypress to trigger a specific action

I need help creating a script that will redirect to a URL when a button is clicked. Below is the code I have developed. HTML : <a id="#next" href="example.com">↵</a> <a id="#previous" href="example.com">↳</a> JS : $(document ...

Press the "show additional content" button on the nytimes.com website using selenium

I'm experiencing difficulty scrolling through this webpage. Once I reach the bottom of the page, I am unable to locate and click on the "SHOW MORE" button using selenium. self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") ...

displaying the download status of a file during the download process with PHP and jquery

Exploring the creation of a unique download manager with PHP and jQuery. In search of a script that enables file downloads with visible progress tracking. The attempted implementation has not yielded the desired results: jQuery function init ...

The JQuery datepicker fails to function properly when the input field is modified from read-only

Utilizing the datepicker in conjunction with an MVC3 application. I aim to keep the input field as readonly until triggered by an edit button. Upon focusing on the field, I want the datepicker functionality to be activated. The code snippet below functio ...

transmitting information via submission with the help of colorbox ajax

HTML <div class="cus_input"> <form id="category_form" method="GET" action="<?php echo base_url(); ?>welcome/find/" > <input type="text" id="category_input" name="q" placeholder=" Find Category"/> <a type="su ...

Leveraging Angular to dynamically adjust the height of ng-if child elements based on parent

I'm struggling with a few things in my current setup. I have a view that consists of 3 states - intro, loading, and completed. My goal is to create a sliding animation from left to right as the user moves through these states. Here is the basic struc ...

Troubleshooting Problems with CSS Printing on iOS Devices

On desktop (both Windows and Mac), the print preview displays correctly. However, on iOS devices, the full width is not shown and there is some blank space above. The issue I'm facing is that I cannot debug this problem using Browserstack. I am restr ...

The SVG syntax underwent alterations following its transmission via email

Can someone please help me fix this code? My visual studio code interpreter seems to be having trouble recognizing the style code within it. <?xml version="1.0" encoding="utf-8"?> <!-- (c) ammap.com | SVG weather icons --> <svg vers ...

including a comma in the jQuery counter

We are facing a challenge with our animated counter. Currently, it counts up quickly to a number without commas for thousands. Despite being well-versed in this area, we are struggling to implement the comma feature. Our existing code functions perfectly ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

Fully compatible with Internet Explorer 6, with a height of

Is there a way to create a div that is always 100% the height of the browser, even if it's empty, and works in IE6? Any suggestions or hacks using CSS? ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

Using -webkit-hyphens: auto in Safari does not function properly when the width is set to auto

I have a situation with an h3 element where I am unsure of its width. As a result, the width is set to auto by default. However, I need the text inside this element to have hyphenation applied to it. This h3 element is within a flex container along with an ...

Create a continuous scrolling tool similar to Google Reader for iGoogle

Do you know how to create an infinite scroll widget similar to Google Reader on iGoogle? This widget should be able to dynamically load data as the user scrolls, and replace the traditional scroll bar with a pair of up and down arrows. The HTML structure ...

Background images at 100% width are not causing horizontal scrolling issues

I've come across an interesting problem. I created a quick screen recording to illustrate: Essentially, when you specify a min-width and the viewport width falls below that limit, a horizontal scroll bar appears. This behavior is expected, but when s ...

Exploring the different ways to compare data with the load() method

I am faced with a coding dilemma. I have two pages: data.php and index.html. The data.php page contains a single value (let's say 99), while the index.html page uses jQuery to dynamically load the data from data.php into a div called "data" every 2 se ...

Steps to eliminate the select all checkbox from mui data grid header

Is there a way to remove the Select All checkbox that appears at the top of the checkbox data column in my table? checkboxSelection The checkboxSelection feature adds checkboxes for every row, including the Select All checkbox in the header. How can I ...

Is there a way to use jQuery to determine if the selectAll checkbox is selected after manually selecting all checkboxes?

How can I accomplish this task? I believe I am capable of doing it. <input type='checkbox' id='selectAll'/> <input type='checkbox' id='select1' class='select'/> <input type='checkbox&apo ...

Assigning the style of the parent element based on the child element

Currently, I am attempting to develop a customized dropdown field and here is the code I have come up with: const list = document.querySelector('.list'); const listItems = list.getElementsByTagName('p'); document.querySelector('# ...