Issue with onresize event not triggering when checking window width

After successfully attaching the onresize listener to the body tag, I encountered an issue when I modified my code to access the window.innerWidth and window.innerHeight properties. Strangely, my resize event only fires once.

<script type="text/javascript">
    function showMsg()
    {
        document.write((window.innerWidth / window.innerHeight) * 100 + "%");
    }
</script>
<body onresize="showMsg()">

Answer №1

It's logical, have you attempted reviewing the source code of your page after the function has completed? The body tag may no longer be present - taking your event listener with it (or it may still be in memory, hanging uselessly).
Try connecting it to the window.

window.onresize = function()
{
    document.write((this.innerWidth/this.innerHeight)*100+'%');
};

In older versions of a once very popular browser, attaching event listeners to the window object could lead to memory leaks. The window object is never completely destroyed more information available here if needed.

How can the memory issue be resolved?

(function(win)
{
    win.onresize = function()
    {
        document.write((this.innerWidth/this.innerHeight)*100+'%');
    };
    if (win.attachEvent)
    {
        win.attachEvent('onbeforeunload',(function(self)
        {
            return function freeMem()
            {
                self.onresize = null;
                self.detachEvent('onbeforeunload',freeMem);
            };
        })(win));
        return;
    }
    win.addEventListener('beforeunload',(functio(self)
    {
        return function freeMem()
        {
            self.onresize = null;
            self.removeEventListener('beforeUnload',freeMem,false);
        };
    })(win),false);
})(this);//this points to current window

I understand, it may look messy, but I have tested this method and it works - Thanks to IE for that. Technically, the closures passing win to self could be omitted, but I have included it to be absolutely certain. Once the onbeforeunload event triggers and the handler returns, all functions and references go out of scope, giving the GC's no reason to not free the memory.
It may be excessive in most cases, but just in case someone finds it useful, I decided to share it here... :-P

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

Dealing with Sideways Overflow Using slideDown() and slideUp()

Attempting to use slideUp() and slideDown() for an animated reveal of page elements, I encountered difficulty when dealing with a relatively positioned icon placed outside the element. During these animations, overflow is set to hidden, resulting in my ico ...

Discovering the vacant fields within a database by looping through them

My goal is to download a .pdf document from the external database Contentful by utilizing an HTML link on a user interface. The issue arises when certain fields inside Contentful do not always necessitate a pdf document. In these cases, the field remains ...

What is the best approach for sending a binary image post request to an API using nodejs?

I am receiving the image binary in this manner: axios.get("image-url.jpg") Now, I want to utilize the response to create a new POST request to another server const form = new FormData(); const url = "post-url-here.com"; form.appe ...

Efficient arrow function usage in jQuery map functionality

Looking to implement an arrow function in jQuery's map function. However, after trying the following code snippet, titlesText ends up being the correct length but with empty strings: let titles = $(panelBody).find('h4'); let titlesText = $(t ...

Starting a typescript class with an already existing object - a step-by-step guide

Although my question may seem similar to previous ones, I have not found the answer I am looking for, so I am posting it here. Here is my example: Class A{ id:number; name:string; } Class B{ id:number; name:string; age:number; grade:number; } ...

Output the JSON string retrieved from a specified URL

I'm currently working on using ajax to retrieve and parse JSON data from a specific URL. I am looking for assistance on how to store the parsed array into a variable. Any guidance or suggestions would be greatly appreciated. Thank you! function rvOff ...

Press the button to dynamically update the CSS using PHP and AJAX

I have been facing challenges with Ajax, so I decided to switch to using plain JavaScript instead. My goal is to create a button on a banner that will allow me to toggle between two pre-existing CSS files to change the style of the page. I already have a f ...

Guide on invoking a function in a PHP file using jQuery's load method

I am having trouble displaying the data retrieved from the database. There is a function called "getComments(page)" in the getComments.php file, where 'page' is an integer parameter corresponding to the chosen database. I need to call this functi ...

Information not reaching the server from the form

Whenever a user clicks on a button within the search results of a query, a form pops up in a modal. This form consists of three input fields and additional fields that are added to it through ajax when the submit button is clicked. In my Django application ...

Extracting Parameters using JQuery's load Method

On a webpage, I am attempting to load a jsp page (another.jsp) within a div element while passing parameters. $("#div").load('another.jsp?a=1&b=2'); Despite trying various methods multiple times, I have not been able to get the desired outc ...

Performing a multitude of if statements simultaneously consistently results in an undefined outcome after the sixth iteration

Oops! I can't believe I forgot my original question! Every time I run the sixth if statement in my code, I encounter a typeError Undefined. Interestingly, when I switch the positions of the fifth and sixth statements, the if(!data.body.main) condition ...

Can Authorization be Combined with Filtering in a Node.js RESTful API?

In my current setup, I have a web application communicating with a RESTful API to interact with the database. The frontend of the web app uses Angular HTTP to post/get/put data to the backend, which then manages authentication, interacts with the API, and ...

jQuery plugin modifies keypress events

I have integrated the Jquery ImgAreaSelector plugin into my website. Within my site, I have implemented several keypress triggers using jquery. For example: $(document).bind('keypress', 'S', function(){ alert("You have pressed S key ...

What is the memory allocation for null values in arrays by node.js?

Continuing the discussion from this thread: Do lots of null values in an array pose any harm? I experimented with node.js by doing this: arr=[] arr[1000]=1 arr[1000000000]=2 arr.sort() However, I encountered the following error: FATAL ERROR: JS Alloca ...

What is the best way to implement setState in this scenario?

Receiving warnings in the console that say: Avoid changing state directly. Instead, use setState() method: react/no-direct-mutation-state When I tried changing this.state.turn = this.state.turn === 'X' ? 'O' : 'X'; to this.s ...

Incorporate a horizontal scrollbar feature within an HTML section

Currently, I am in the process of learning vue js and would like to create a layout that includes two sections. The first section should occupy 3 grids on the screen, be fixed, and not scrollable, with a division into 4 vertical parts. The second section s ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Trouble with Updating Div Content?

Within my HTML code, I have included this JavaScript snippet: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script> var auto_refresh = setInterval( function() { $('#loaddiv').fadeOut ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...