Differences between JavaScript closures and traditional functions

Recently, I came across an example of JavaScript closure that left me puzzled.

The example code is as follows:

function makeSizer(size) {
  return function() {
    document.body.style.fontSize = size + 'px';
  };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

If you click on the element `size-12`, for example, it triggers the anonymous function inside `makeSizer` which changes the font size to 12 pixels. Simple enough, right?

But what's confusing to me is when I make a slight alteration to the original code:

function makeSizer(size) {

    document.body.style.fontSize = size + 'px';

}

And then call `makeSizer(12)` directly instead of assigning it to `size12` for the click event, it no longer works.

I understand that this showcases the power of closures in JavaScript, but why does my modified version not produce the desired result?

Sincerely, Charles.

Answer №1

The onclick attribute requires a function to be provided. In the second example given, makeSizer(12) is not a function but rather a function call. To make it work properly, you should enclose it within an anonymous function like this:

document.getElementById('size-12').onclick = function() {makeSizer(12);};

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

Is it feasible to cancel or clear the queue for a jQuery fadeOut function after a delay is specified? If so,

Can anyone help me out with this question? Is there a way to eliminate the delay in chaining? Mn.Base.TopBox.show = function(timedur){ $('#element').fadeIn().delay(timedur).fadeOut(); } Mn.Base.TopBox.cancelFadeout = function(){ } I&apos ...

The SMTP request for a one.com domain email is experiencing issues when sent from the render.com server

I have set up an Express JS server on render.com to handle SMTP calls to an email service hosted on one.com with a custom domain. Utilizing nodemailer to manage the SMTP call: app.post("/send-mail", validate(schema), (req, res) => { console. ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...

Prevent dropzone from refreshing the page

For the past few days, I have been scouring the internet for solutions on how to prevent a page from automatically reloading after an upload. Despite finding various methods, I have been unsuccessful in resolving this issue. Although I am following the st ...

I could really use some guidance on how to begin with the Node.JS app file in BlueMix

After delving into JS tutorials, I feel comfortable with the syntax and approach. Now, my focus is on utilizing Node.JS to develop an app using BlueMix. While I consider myself proficient in Java, web programming is uncharted territory for me, leaving me s ...

How to remove an event listener that was added within a function in JavaScript?

I am encountering an issue while trying to remove an event listener that was created inside a function. Oddly enough, it works perfectly when I move the event listener outside of the function. See the example below: <body> <div id='myDiv&apo ...

Should the element be scrolled beyond a fixed-positioned element

Is there a way to determine if an element is scrolled behind another element that is fixed at the top? I am looking to trigger some javascript when an element is positioned below a fixed element and every height or scrollTop thereafter. I am attempting t ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

executing npm tasks concurrently

Trying to demonstrate running npm tasks in parallel is my current task. I should be able to achieve this using "&" for parallel and "&&" for series. { "name": "npm", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "co ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

Loading custom places in ArcGIS from a file or database

Hey there, I was wondering about loading custom places with Arcgis similar to Google maps loading from a .xml file. I noticed that Arcgis uses examples saved in .json format, but when I tried putting the example .json on my local server it wouldn't lo ...

Babeljs encountered an error: TypeError - The super expression should be a function or null, not undefined

Currently, my project involves implementing multiple-files inheritance in ES6 using Node.js and Babel. Babel is used to convert the ES6 code to ES5 since Node does not fully support ES6 yet. Import/export statements are used to connect the different files ...

When a button is clicked, the event is not triggered within a FirefoxOS application

Despite functioning perfectly on Firefox for desktop, my application encounters issues when tested on my ZTE Open C (Firefox OS 1.3). Pressing the button does not trigger any action, while onmouseup and onclick events work flawlessly. Even attempts to bin ...

selecting a radio button and saving its value into a JavaScript variable

How can I assign the return value from a JavaScript script function to a variable inside the HTML body? The function will return the selected variable, but how can I assign it to a variable within my HTML body? <body> <form action="somepage.php ...

Issues with rendering HTML5 drag and drop styles are not visible on a Windows Server 2003 platform

I am currently developing a file upload tool utilizing Valum's Ajax-Uploader as the foundation. The concept is reminiscent of how attaching files works in Gmail. Users should be able to simply drag and drop a file from their desktop into the browser w ...

Requesting the user to repeatedly input their birth year until it is less than the current year

Can anyone help me figure out how to display a prompt until the user enters a birth year that is less than the current year? I've tried using a loop in my code, but I'm having trouble getting it right. Any assistance would be greatly appreciated. ...

Dynamically setting the height of elements using jQuery with incremental values

My Objective: I am trying to dynamically adjust the height of each li element within a ul.container. The goal is to find the tallest li, add 25px to its height, and then apply that new height to all other li elements in the container. This calculation ne ...

Refreshing a <div> element in Django, yet there is no visible update

As I utilize a barcode scanner to add objects to my array list, the data is populated after each scan depending on the scanning speed of the user. To exhibit this data, I have designed a dedicated page. My intention is to avoid refreshing the entire page b ...

React-Bootstrap Table Toolkit Encounter Search Import Issue

I encountered an issue while trying to integrate React Bootstrap Table into my project, resulting in the following error message. Uncaught ReferenceError: arguments is not defined at Object../node_modules/react-bootstrap-table2-toolkit/lib/src/search/Sea ...