Tips for implementing and utilizing onclick functions in EJS

My goal is to develop a trivia game with interactive features. I aim to enable users to click on an answer, which will trigger a border effect and increase the points variable.

Below is the layout of the entire page:

    <% include ../partials/boilerplate %>

<%  var points = 0; 
correctAnswer = (num) =>  {     
    document.getElementById(`correctAnswer${i}`).style.border = "5px solid black";
    points+=1
 } %>


<div class="triviaContainer">
    <h1>WELCOME TO TOP FACT </h1>
    <% var i =0; data.forEach(question =>{  %>
<div class="questionRow">
    <div> <%= question.question %></div>
</div>
<div class="questionRow1">
    <div class="correctAnswer<%= i+=1 %>" onclick=  <%= correctAnswer(i) %>  > A: <%= question.correct_answer %></div>
    <div>B: <%= question.incorrect_answers[0].incorrect_answer %></div>
</div>
<div class="questionRow2">
    <div>C: <%= question.incorrect_answers[1].incorrect_answer %></div>
    <div>D: <%= question.incorrect_answers[2].incorrect_answer %></div>
</div>


 <%   }) %>
   </div>

I am looking for a method to use this function by clicking on it and providing a parameter indicating the respective question, since questions are dynamically generated in a loop as demonstrated above.

<%  var points = 0; 
correctAnswer = (num) =>  {     
    document.getElementById(`correctAnswer${i}`).style.border = "5px solid black";
    points+=1
 } %>

Here is the inline onclick code snippet:

 <div class="correctAnswer<%= i+=1 %>" onclick=  <%= correctAnswer(i) %>  > A: 
<%= question.correct_answer %></div>

Encountering an error while using EJS:

    ReferenceError: /Users/jdiperi88/wdi/UNIT_02/projects/trivia/views/trivia/trivia-index.ejs:17
    15|     </div>
    16|     <div class="questionRow1">
 >> 17|         <div class="correctAnswer<%= i+=1 %>" onclick=  <%= correctAnswer(i) %>  > A: <%= question.correct_answer %></div>
    18|         <div>B: <%= question.incorrect_answers[0].incorrect_answer %></div>
    19|     </div>
    20|     <div class="questionRow2">

document is not defined
    at correctAnswer (eval at compile (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:24:9)
    at data.forEach.question (eval at compile (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:38:26)
    at Array.forEach (native)
    at eval (eval at compile (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:30:23)
    at returnedFn (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:580:17)
    at tryHandleCache (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:223:34)
    at View.exports.renderFile [as engine] (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/ejs/lib/ejs.js:437:10)
    at View.render (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/express/lib/view.js:128:8)
    at tryRender (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/express/lib/application.js:640:10)
    at Function.render (/Users/jdiperi88/wdi/UNIT_02/projects/trivia/node_modules/express/lib/application.js:592:3)

What would be the optimal solution to resolve this issue?

Answer №1

EJS forms the view using JavaScript on the server side and then sends it to the browser for rendering. Its main purpose is not to perform any other actions beyond that. The functionality you are aiming for is typically accomplished by using JavaScript within a <script> tag on the client side.

You can achieve something similar to this (note: untested code):

<script>
var points = 0; 
function markCorrectAnswer(num){     
    document.getElementById('correctAnswer' + num).style.border = "5px solid black";
    points += 1;
}
</script>

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

Is it possible to showcase dates within input text boxes prior to POSTing the form?

I am currently working on a form that posts to a PHP script by selecting a date range. For a better understanding, you can check out my visual representation here. Before the data is posted, I would like to display the selected dates in empty boxes or inpu ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Entering text into the input field with the string "Foo"<[email protected]> is not functioning correctly

The text in my input is initially filled with this string "foo foo"<<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f2920200f29202061263b">[email protected]</a>>. However, after an insert, the string now l ...

pictures showcased in a grid that dance and sway

Hey everyone, I wanted to ask about images on a website that have a unique effect when you hover over them. On the site follow your feet website, there is a grid section of destinations and when you move your mouse over a destination, it suddenly expands a ...

In Internet Explorer 10, it is not possible to access the document.links using the link's id; it can only be accessed using the

Why does the following code work in FireFox 23.0.1 and Chrome 29, but not in IE 10? <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript"> function loadFile1(){ a ...

Implement scroll bar functionality on canvas following the initial loading phase

I am currently working with canvas and I need to implement a scroll bar only when it is necessary. Initially, when the page loads, there isn't enough content to require a scroll bar. My project involves creating a binary search tree visualizer where u ...

Implementing NPM commands in Jenkins using shell scripting

Whenever I attempt to run the "npm" command, I encounter a syntax error. Users/Shared/Jenkins/Home/workspace/projectName/npm test ^^^^ SyntaxError: Unexpected identifier This is the Jenkins Build shel ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

Can AJAX be used when submitting an HTML form with a select input field?

I have been working on an Ajax search suggest input and have successfully implemented it. However, I would like to tweak the script so that when a suggestion is selected, the form auto-submits. Below is my JavaScript code: <script> function suggest ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Discovering distinct colors for this loading dots script

Looking for assistance with a 10 loading dots animation script. I'm trying to customize the color of each dot individually, but when I create separate divs for each dot and control their colors in CSS, it causes issues with the animation. If anyone ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

"Challenges with Full-Width Dropdowns in Multi-level Mega Menus

I am currently attempting to design a multi-level mega menu that spans the full width of the screen, while keeping the content within it restricted to a maximum width of 1240px. I have managed to set the content to the maximum width, but I am facing challe ...

initiate changes to the application's style from a component nested within the app

I'm looking to update the background color of the entire page, including the app-nav-bar, when I'm inside a child component. When I navigate away from that component, I want the default style to be restored. Any suggestions on how to achieve this ...

What could be causing justify-content: flex-start; to not function as expected?

Can someone help me with my flexbox navbar? I set the justify-content property to flex-start, but the content inside the container is not aligning correctly. You can see the output and code here: output html, body { backgr ...

Setting maxFontSizeMultiplier for all Text components

Is there a way to apply the prop maxFontSizeMultiplier={1} to all instances of <Text/> in my app without the need for a custom component? ...

Incorporating fresh CSS styles through Selenium

I am attempting to showcase all the prices available on this page using Selenium and Chrome in order to capture a screenshot. By default, only 3 prices are visible. Is there a way to disable the slick-slider so that all 5 prices can be seen? I have tried r ...

Click here to start your Django download now

I am looking for a way to monitor the number of times a file has been downloaded. Here is my plan: 1) Instead of using <a href="{{ file.url }}" download>...</a>, I propose redirecting the user to a download view with a link like <a href="do ...

What is the best way to set up a session using jQuery?

I've been troubleshooting my code and I can't seem to figure out why the jquery.session.js file isn't working. Can someone help me find a solution? $.session.set('rmng_time', remaining_seconds); alert("j session "+$.sessi ...