0

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.

F.Mi
  • 51
  • 9

1 Answers1

1

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?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks the link you sent really helped. Now I'm just easily calling the "optionClick()" function in the onclick event of the button, and there's no need for all those complicated steps. `` – F.Mi Nov 18 '21 at 23:17