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

402
Views
Calling an external js function as ejs onclick event

I have a nodejs application that renders an ejs file called main.ejs including a button. I'd like to declare a function in an external javascript file that I can call it in the onclick event of that button(in main.ejs). But every time I run the app, by rendering the page, that function will be called automatically, but when I click on the button it won't be called!

(I need to mention that I have already tried writing this function directly in main.ejs in a script tag, and it perfectly works. But I'm persisting in moving it to a respective js file)

functions.js (the external js file)

function optionClick() {
    console.log("Yoohooo!!");
}

module.exports = {
    optionClickFunc: optionClick
};

server.js

var functions = require('./public/functions');

app.get('/question', (req, res) => {
 res.render('main.ejs', {
                data: {
                   function: functions.optionClickFunc
                }
            });
});

main.ejs

<button id="submit-button" onclick="'<%= data.function() %>';"> START </button>

And whenever I have this url in my browser: http://localhost:3000/question, I see the log message("Yoohooo!!") printed in the console without clicking on the button! While it doesn't print the message when I click the botton!!

Any idea? I really appreciate your time.

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

0

data.function is a function and when you call it in your server-side-code, you call it in your server side code.

When you write HTML you need to write strings and the string representing the value of the onclick attribute needs to be JavaScript source code. (data.function, as mentioned, is a function not a string of source code.) The client will compile that source code and execute it.


Your server-side and client-side code might both be written in JavaScript, but they are two different programs running in two different environments (Node.js and the browser) which will usually (less so during development) run on two different computers.

Related: What is the difference between client-side and server-side programming?

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!