Acquiring the event parameter from a function that is not a callback (regular function invocation)

In order to extract the event argument from a standard function invocation, developers often refer to callback functions as a solution:

document.addEventListener('something', function(e){e.target.parentNode...etc});

The following snippet showcases my implementation:

<div class="options">
    <div onclick="controller.question_type('circleTheCorrectAnswer')">Circle The Correct Answer</div>
</div>

<script type="text/javascript">
 const controller = (()=>{

  const question_type = (x)=>{
    console.log(x.target.parentNode);
    console.log(x.target);
  }

  return {
    question_type: question_type
  }

 })();
</script>

Answer №1

When looking at your code snippet,

<div onclick="controller.changeQuestionType('selectTheRightAnswer')">

You can think of it as being similar to

document.addEventListener('click', controller.changeQuestionType('selectTheRightAnswer'));

The issue with the above code is that the function called by controller.changeQuestionType() does not return a function, causing the event handler to have no target.

To fix this, you could modify the changeQuestionType function like so:

const changeQuestionType = (type) => {
  console.log(`Selected type: ${type}`)
  return (event) => {
    console.log(event.target.parentNode);
    console.log(event.target);
  }
}

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

Looking to create a JSON array and iterate through its elements

I am in need of creating a state for multiple elements displayed on a web page. The states are limited to 1 or -1. My approach is to generate a JSON array on the server side and then embed it into my .aspx page like this: var someArray = { 100:-1, 1001: ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Using Froala events in Angular 2: A guide

Currently, I am incorporating Froala into my Angular 2 project. I have managed to upload an image successfully but am encountering issues triggering the image.uploaded event. The Froala document provides an example of how the event should be implemented: ...

Issue with ASP Handler failing to send error message to ajax request in a managed hosting environment

When making an ajax call to a Handler, I am trying to return an error from a Stored Procedure in SQL. Below is the code for my ajax call: $.ajax({ url: "Handlers/MyHandlerCall.ashx?QueCtrlType=1" co ...

I'm having some unusual issues with my Next.js installation - can anyone help me troubleshoot and find a solution?

Having just started using Next.js, I am facing difficulties in accessing my second page named auth.js (through localhost:3000/auth). In my "page.js" installed as "index.js" (Whole Directory), there is a button that should lead to /auth: <li> < ...

Determine whether an image is retina or non-retina using just one picture

Is it possible to use just one picture that is already optimized for retina displays, but automatically resize or crop down to a non-retina version when viewed on a non-retina screen? I'm facing this issue specifically with IE while using a PC. The im ...

The parameter of type 'X' cannot be assigned to the argument of type 'Y'

I've defined the following types: export type Optional<T> = T | null; along with this function updateBook( book: Array<Optional<Hostel>>) which I'm using like this let book: Hostel | null [] = [null]; updateBook(book) Ho ...

How can I send back multiple error messages from a pug template in a node.js application with Express?

I am currently working on validating inputs from a form on a Node.js web server using Pug.js and Express.js. The issue I am facing is that when there are multiple problems with the user's input, only the first error is displayed to the user. How can I ...

How can we retrieve the coordinates of the top-left and bottom-right corners based on the given bounds

Looking to retrieve the X and Y coordinates of the top-right & bottom-left corners of a text box based on the bound value. For instance: [84,672][1356,889] Is there a straightforward JavaScript function that can efficiently extract these values into sepa ...

Please confirm the modal by adding a textarea with a newline in SweetAlert2

Every time I attempt to add a line break in the textarea input field, the modal pops up. I have tried adding these lines of code as well, but nothing seems to be working: allowEnterKey: false, focusConfirm: false, Does anyone have any advice for solving ...

A guide on effectively mocking functions in Jest tests with Rollup.js

I am currently in the process of developing a React library called MyLibrary, using Rollup.js version 2.58.3 for bundling and jest for unit testing. Synopsis of the Issue The main challenge I am facing is with mocking a module from my library when using j ...

Learn how to toggle a specific div by clicking on an image generated from an ngFor loop in Angular version 11

One issue I am facing is that I have multiple sections containing image info and details. When I click on a specific image, the corresponding details should toggle. Everything works fine, however, if I click on another image without closing the previous ...

Display a section of a string as the result

I have a JavaScript challenge where I need to extract the value inside li tags using only JavaScript. Can anyone guide me on how to achieve this? JavaScript var string = "<div><li>First LI</li><li>Second LI</li></div>" ...

Is it possible to translate the IIFE functions of threejs into ES6 format?

I'm currently facing a challenge in breaking down my threejs project into smaller modules. One specific function that I'm struggling with is the following: var updateCamera = (function() { var euler = new THREE.Euler( 0, 0, 0, 'YXZ&apos ...

Tips for Converting a JavaScript Array into JSON

I am dealing with data structured like this: "team": "Yankees" "players": ["jeter", "babe ruth", "lou gehrig", "yogi berra"] In my code, I extract these values from a form where they ar ...

Determining When the Collapse Transition in Material UI 5 is Complete

Snippet <Collapse in={expanded} onTransitionEnd={() => console.log('finished')} > <div>foo</div> </Collapse> Error Detection The callback function (onTransitionEnd) is not triggered af ...

Is there a way to create a dropdown menu that stretches across the entire page width when the burger menu is hovered over?

Is there a way to create a full-width dropdown menu that appears when the burger icon is clicked, while still maintaining the close function? (The dropdown menu and burger icon should transition smoothly when clicked) Here are the JavaScript functions for ...

Navigate through pages with the help of AJAX in PHP

Hello everyone, I am currently working on a jQuery game project and I am in the process of creating a welcome screen. To switch between pages, I am utilizing AJAX. However, while the page transitions are functioning correctly, the main game elements on my ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

Using Vue.js to dynamically populate all dropdown menus with a v-for loop

Getting started with vue.js, I have a task where I need to loop through user data and display it in bootstrap cols. The number of cols grows based on the number of registered users. Each col contains user data along with a select element. These select ele ...