Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly.

Although the following code runs the function, the Event Listener is not functioning as expected:

window.addEventListener("resize", (function () {
document.getElementById("divMenu").innerHTML = document.getElementById("divTop").offsetWidth
})())

This function is crucial for setting a dynamic CSS style necessary for website formatting. The "resize" function must be executed upon loading. Should I combine this into one self-invoking function, or create a separate Self-Invoking Function to call on the Event Listener?

Answer №1

By invoking the function immediately, its return value is placed in its spot (

window.addEventListener('resize', undefined)
). It's better to define your function outside of the event listener and then add it before calling it.

function onResize() {
  document.getElementById('divMenu').innerHTML = document.getElementById("divTop").offsetWidth;
}
window.addEventListener('resize', onResize);
onResize();

It is technically possible to make this work using a self-invoking function, but it can be confusing and I would not recommend it.

window.addEventListener('resize', (function onResize() {
  document.getElementById('divMenu').innerHTML = document.getElementById("divTop").offsetWidth;
  // This works because it returns a function
  return onResize;
})());

Answer №2

Your immediately invoked function expression (IIF) is returning undefined, but the event listener requires a function or a reference to a function. Make sure to add a return statement to your IIF or pass a function:

Example with an anonymous function:

 window.addEventListener("resize", function () {
    document.getElementById("divMenu").innerHTML = document.getElementById("divTop").offsetWidth
 }))

IIF that returns a function:

 window.addEventListener("resize", (function () {
 return function(){
    document.getElementById("divMenu").innerHTML = document.getElementById("divTop").offsetWidth
 }
 })())

Improved version with immediate invocation on startup:

window.addEventListener("resize", (function () {
  function set_innerHtml(){
    document.getElementById("divMenu").innerHTML = document.getElementById("divTop").offsetWidth
  }
  set_innerHtml();
  return set_innerHtml;
})())

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

Manage numerous canvas animations

Is there a way to interact with an already drawn Canvas animation? I am attempting to create 3 distinct tracks that can be controlled by a "Start" and "Stop" button. However, when I click the Start button on the first canvas, it triggers the last canvas in ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

I find the SetInterval loop to be quite perplexing

HTML <div id="backspace" ng-click="deleteString(''); decrementCursor();"> JS <script> $scope.deleteString = function() { if($scope.cursorPosVal > 0){ //$scope.name = $scope.name - letter; ...

Interpolating backticks in Javascript allows for constructing a URL containing empty spaces

When utilizing string interpolation with backticks to construct a URL that sends data to a django endpoint, the resulting URL contains unnecessary whitespace and a new line. The problematic JavaScript code is as follows: (function (window, document, unde ...

Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code: <ul ondrop="drop(event)" ondragover="allowDrop(event)"> <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)"> <div class="product-infos"> ...

Switch the selected option in JQuery UI dropdown using a clickable button

I have a code snippet that is almost working. My goal is to change the selection of a JQuery dropdown select combobox using a separate button named "next". What I want is for the JQuery dropdown to automatically switch to the next selection every time I c ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

Dynamic and static slugs in Next.js routing: how to navigate efficiently

I am facing a scenario where the URL contains a dynamic slug at its base to fetch data. However, I now require a static slug after the dynamic one to indicate a different page while still being able to access the base dynamic slug for information. For Ins ...

Vue.JS - Dynamically Displaying Property Values Based on Other Property and Concatenating with

I have a reusable component in Vue.js called DonutChart. <donut-chart :chartName="graphPrefix + 'PerformanceDay'" /> The value of the property graphPrefix is currently set to site1. It is used as part of the identifier for the div id ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...

What is the best way to implement a switch that can simultaneously display both the on and off positions?

I need help customizing a toggle switch element in CSS. I want the first row to display as on (blue color) and the second and third rows to be displayed as off or grey. So far, my attempts to modify the CSS code have been unsuccessful. .switch { posi ...

Save this page for later by using JavaScript to create a

Does anyone have a solution as to why window.location.href does not save the current webpage URL as a bookmark? Thank you ...

Error handling middleware delivering a response promptly

Issue with my express application: Even after reaching the error middleware, the second middleware function is still being executed after res.json. As per the documentation: The response object (res) methods mentioned below can send a response to the cl ...

One creative method for iterating through an array of objects and making modifications

Is there a more efficient way to achieve the same outcome? Brief Description: routes = [ { name: 'vehicle', activated: true}, { name: 'userassignment', activated: true}, { name: 'relations', activated: true}, { name: &apos ...

What is the best way to retrieve the values of various input fields using their numbered IDs and then store them in a MySQL

I attempted to design a form that allows for multiple inserts, where users can add as many titles and languages as they desire by entering a number. The display of titles and languages is functioning correctly, but I am struggling to retrieve the individua ...

Exclude React Native module and import web module in Webpack

Currently, I am facing a challenge in my project where I need to alias a different package specifically for a webpack configuration. The issue revolves around the VictoryJS library (link: https://formidable.com/open-source/victory/). In my React Native app ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...

Calculating variables in JavaScript

Explanation from Mozilla Documentation: console.log((function(...args) {}).length); // The result is 0 because the rest parameter is not counted console.log((function(a, b = 1, c) {}).length); // The result is 1 because only parameters before th ...