I created a basic JavaScript closure script, but it refuses to execute. Can anyone point out my mistake?

I recently started learning Javascript and have been practicing closures. I created a simple code where clicking on a link should increase the font size of the document's body. However, I seem to be making a mistake somewhere and can't figure out what it is.

    <!DOCTYPE html>
    <html>
       <head>
          <style>
             body {
             font-family: 'Times New Roman', Times, serif;
             font-size: 10px;
             background-color: bisque;
             color:black;
             }
          </style>
</head>
       <body>
          <p>HELLO!! I AM CHANGING MY SIZES.</p>
          <a href="#" id="size-12" onclick="changeSize(12)">Size 12</a>
          <a href="#" id="size-14" onclick="changeSize(14)">Size 14</a>
          <a href="#" id="size-16" onclick="changeSize(16)">Size 16</a>
          <script>
             function changeSize(size) {
                   return function () {
                       document.body.style.fontSize = size + 'px';
                   }
               };
          </script>
       </body>
<html>

Answer №1

If you're currently returning a function and not calling it, make this simple change to call the function:

onclick="changeSize(12)()"

By doing this, changeSize(12) will return the inner function, and then using the second set of parentheses will call the inner function :)

UPDATE: As others have pointed out, there's no real need to return an inner function. If the content of the function changeSize() were something like:

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

it would be much more concise

Answer №2

One benefit of utilizing a function created from a closure is to develop a function that "locks in" a more general function with specific parameters. Adjusting the handler attributes by adding an extra pair of parentheses at the end may resolve the issue, but it defeats the purpose of using a function-generating function.

Instead, consider creating a series of predefined functions to be used in your HTML:

      <script>
         function changeSize(size) {
               return function () {
                   document.body.style.fontSize = size + 'px';
               }
           };

         var size12 = changeSize(12);
         var size14 = changeSize(14);
         var size16 = changeSize(16);
      </script>

You can now implement these pre-made functions in your HTML code:

      <a href="#" id="size-12" onclick="size12()">Size 12</a>
      <a href="#" id="size-14" onclick="size14()">Size 14</a>
      <a href="#" id="size-16" onclick="size16()">Size 16</a>

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

LOGIN operation in Mongoose with Node.js fails due to a null value in

//register new user app.post('/signup', async function(req,res,next) { const saltRounds = 10; let password = req.body.password; let userEmailExist = await user.findOne({ email: req.body.email }); if(userEmailExist) return res.s ...

Submitting form data as JSON using Axios' POST method

I am facing an issue while trying to send data from an HTML form to a REST backend service that only accepts JSON. After setting up my form as follows: <form name="form" > <input type="text" placeholder="Name" value="name" size="60"/></ ...

What is the process for finding GitHub users with a specific string in their name by utilizing the GitHub API

I'm looking to retrieve a list of users whose usernames contain the specific string I provide in my query. The only method I currently know to access user information is through another endpoint provided by the GitHub API, which unfortunately limits t ...

This method or property is not supported by the object - How to call an Applet in Internet Explorer 9

cmd > java -version Java Version : "1.7.0_11" (Updated) Java(TM) SE Runtime Environment (build 1.7.0_11-b21) Java HotSpot(TM) Client VM (build 23.6-b04, mixed mode, sharing) browsers = IE7,IE8,IE9 (The functionality works smoothly in Google Chrome and ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

What steps can I take to ensure that WebStorm properly recognizes a package's functions?

No matter what I do, WebStorm refuses to stop throwing inspection warnings when I try to use the JOI package in my node.js project. The code runs fine and there are no runtime errors, but the warning persists. I have updated the package, explicitly install ...

Using Vue to dynamically set custom validation messages

I am currently tackling the challenge of modifying the default invalid text for form inputs with the code snippet provided below. The method I am attempting works when the text is static, but the text in my case must be dynamic, requiring a prop/data value ...

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Substitute phrases with hyperlinks using JavaScript (or Ruby)

After researching numerous resources on SO, I have managed to come up with a solution that is very close to working. My goal is to replace words/phrases within a <p> tag with links using jQuery after the page has loaded (although I am open to a Ruby ...

Is there a method to refresh the image in the template?

I am currently working on generating various images using canvas. Is there a way to display these images in real-time on my main.pug template without having to reload the page every time an image changes? const Canvas = require('canvas') , Ima ...

Ways to utilize useEffect after a modification in the localStorage value

In my react app, I'm storing user data filters in localStorage. I want to use useEffect to detect when that data changes. How can I properly activate this effect? I attempted the following: useEffect(() => { if (rawEstateObjects.length &&a ...

Implementing dynamic input elements in React components and managing state changes

I am currently working on a React component that includes simple input fields to track state for an AJAX call. There is also a button that, when clicked, generates a new set of input fields identical to the original ones. As a React novice, I initially at ...

Error: AJAX response shows as NaN, indicating that the requested resource was not found

Attempting to create a search engine using AJAX. When typing in the search box, nothing happens. After inspecting the element and opening the console, an error message is displayed: script.js:19 GET http://localhost/var/www/html/pendaftaran-siswa/NaN 404 ( ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Changing the entire content of a webpage from the server using AJAX

I am looking to update the entire page content with the click of a button, transitioning from Words.html to SelectNumber.html This snippet is from Words.html <html> <head> <meta charset="UTF-8"> <title>Number Game< ...

.ajax() triggers a page refresh upon pressing the ENTER key

Utilizing Ajax to update the database with a new folder leads to page refresh when hitting ENTER. On the form, I have onkeypress="if(event.keyCode==13) savefolder();". Below is the Javascript code where pressing enter calls savefolder function that sen ...

Is it possible to evaluate the complexity of automating the user interface of a web application?

What are some common indicators of the challenges involved in automating the frontend of a web application? One example could be ensuring that all “critical” elements have stable ID attributes that do not change frequently. Are there any other similar ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

Spin and flip user-submitted images with the power of HTML5 canvas!

I am currently working on a profile upload system where we are implementing image rotation using the HTML5 canvas object with JavaScript. Although the uploaded image is rotating, we are facing issues where parts of the image are being cut off randomly. So ...

A guide to setting up checkbox input in Vue 3 so that it toggles between checked and unchecked states when an

I'm in the process of creating a div container that will contain both an image and a checkbox input element. The checkbox input has a click handler that passes a value to a function, as well as a :value binding which sends the value to an array named ...