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.