Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
Pass function as argument to another function called inside the first one

I have a function that creates a button with an "onclick" action that calls a second function. This second function will recieve parameters of the first one (includind a function). Just like this:

function funcOne(argFunc, customMsg) {
    let div = document.createElement('div');
    let button = `<button onclick='funcTwo(`+argFunc+`','`+customMsg+`)'>Go!</button>`;
    div.innerHTML = button;
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}

Then, calling funcOne:

funcOne(function(customContent) { alert(customContent) },
'Hello World');

I get "Uncaught SyntaxError: Unexpected end of input" error here:

let button = <button onclick='funcTwo(+argFunc+','+customMsg+)'>Go!</button>;

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In general, avoid onxyz-attribute-style event handlers. Always avoid them when you have a function (rather than string) you need to hook up dynamically. They have several issues, not least that they can only call global functions.

Instead, use modern event handling. There's also no need for HTML parsing:

function funcOne(argFunc, customMsg) {
    const div = document.createElement("div");
    const button = document.createElement("button");
    button.textContent = "Go";
    button.addEventListener("click", () => {
        funcTwo(argFunc, customMsg);
    });
    div.appendChild(button);
    document.body.appendChild(div);
}

function funcTwo(argFunc, customMsg) {
    argFunc(customMsg);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!