When I trigger a click event, it doesn't return anything, however, the function works perfectly when I execute a load event

I am having trouble displaying a random word from an array on my webpage. Whenever I click the button, it shows undefined and the console.log of randIndex gives me NaN.

I've been trying to solve this issue but I can't seem to figure out what's wrong. The goal is for the mealBtn to display a meal item above itself when clicked. However, it only shows undefined in the DOM. What baffles me the most is that if I run an initialize function on window.load, everything works perfectly as expected.

    //load a menu item when the window loads
    window.addEventListener('load', init);

    const mealBtn = document.getElementById('mealBtn');
    const currentMeal = document.getElementById('current-meal');
    const message = document.getElementById('message');

    const menu = [
      'Macaroni',
      'Burgers',
      'Chili',
      'Breakfast',
      'Chicken',
      'Take Out?'
    ];

    function init(){
      showMeal(menu);
    }

    mealBtn.addEventListener('click', showMeal);

    //display a random meal from the menu array
    function showMeal(menu){
      const randIndex = Math.floor(Math.random() * menu.length);
      currentMeal.innerHTML = menu[randIndex];
      message.innerHTML = 'How about this?';
      message.style.color = '#003b6f'
    };

When I click the button, I expect to see a menu suggestion right above it on the DOM. It successfully displays the content on the initialization function when the window is loaded but fails to do so when the button is clicked.

Answer №1

mealBtn.addEventListener('click', displayMeal);

When triggered, the event passed to displayMeal is the argument, not dinnerMenu.

You have a choice between:

mealBtn.addEventListener('click', () => displayMeal(dinnerMenu));
// or
mealBtn.addEventListener('click', displayMeal.bind(null, dinnerMenu));

The latter demonstrates partial application, which is concise but may not be immediately clear.

Answer №2

When working with event listener callbacks in JavaScript, it's important to note that they typically accept a single parameter: an object based on the Event (for more information, refer to this link).

For example, when dealing with MouseEvent (specifically the click event), you can utilize the `detail` property which can be accessed as follows:

obj.addEventListener("click", (e) => doSomethingWith(e.detail))

If the Event parameter is not useful in your case and you need to pass custom parameters to the handler, there are various approaches you can take. Tyler's solution provides one way to modify the handler, but alternatively, you could simply use:

mealBtn.addEventListener('click', init);

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

In what situations should the `#` symbol be used to select a DOM element?

There are times when I have to retrieve elements in the following ways: var object = document.getElementById('ObjectName'); Other times, it's done like this: var object = document.getElementById('#ObjectName'); What distinguishes ...

Instructions on creating a vertical height adjustment handle for a website

Is there a way to create a 100% height div that can be divided by a draggable border vertically? Take a look at my fiddle to see what I have so far: http://jsfiddle.net/k5rtbzs5/ This is the HTML code: <div class="column"> <div class="top"> ...

There was a TypeError encountered in a Node application, stating: "Unable to access the 'trim' property of an undefined

Currently, I am developing a JavaScript application that follows the MVC model. In the controllers, there is a userController.js file, and in the models, there is a user.js file which contains a cleanup function. However, I am encountering a TypeError: Can ...

What is the best way to cancel Interval in a React application?

I need help with implementing setInterval in my react redux application. Below is the code snippet from FileAction.js export const SetPath = ({ path, location }) => async (dispatch) => { try { let interval; if (pre_path === path) ...

Leveraging knockout.js to define the width for kendo-ui input wrappers

In the durandal project I'm working on, where JavaScript and HTML are written on separate pages, I encountered an issue with a kendo-combo element. When I initially set the width using the wrapper-input width declaration, it worked perfectly fine. How ...

Obtain the row ID in React's MUI-Datatables

I have a scenario where I am working with a table that displays two buttons, one for deleting and the other for editing a row. For both of these buttons, I need to access the specific row Id. I attempted to utilize customBodyRender but ran into an issue ...

Show InfoWindow on Google Maps by hovering, not clicking

I have a query about integrating Google Maps with a jquery plugin for map display. Everything is functioning correctly, from marker positioning to page reload (with new database queries based on updated map coordinates, etc.) The only issue I'm faci ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

Fill the input field with data retrieved from a json file

I'm working on a Rails app where I need to populate a field with a value from JSON that is returned after clicking on a link. Can anyone point me to a tutorial that explains how to use Ajax correctly for this purpose? Here's my plan: 1. Send a G ...

Having trouble with page reload when implementing Angular Ui Router in Html5 mode with AngularJS?

Within my Angular app, I have implemented Angular UI Router and made use of HTML5 mode to eliminate the "#" from my URLs by utilizing the $locationProvider in the configuration. angular.module('myApp', ['ui.router']) .config(function( ...

The TypeScript factory design pattern is throwing an error stating that the property does not

While working with TypeScript, I encountered an issue when trying to implement the factory pattern. Specifically, I am unable to access child functions that do not exist in the super class without encountering a compiler error. Here is the structure of my ...

Show the subjects' names and their scores once they have been added to a fresh array

Here is my unique code snippet: let fruits: string[] = ['Apple', 'Banana', 'Orange', 'Grapes', 'Mango']; function capitalize(fruit: string) { return fruit.toUpperCase(); } let uppercaseFruits = fruits ...

Clear the default content from a Bootstrap modal form

Each object from the 'myData' array is being used to create divs. Additionally, there is a bootstrap modal with a form for adding an external object. Once this external object is added to the array 'myData', it will be displayed in the ...

Real-time data updates using AJAX in Ruby on Rails

Currently, I am working with Rails and jquery to implement dynamic content using ajax. However, one issue I am facing is extracting the current user ID from the URL For instance, if the URL is www.mywebsite.com/users/20 In my javascript file, I require ...

Navigating to a dynamically inserted element within a React component

I've implemented this code that I trigger on a button click to smoothly scroll to the bottom of a page: const el = useRef<HTMLDivElement>(null); const ScrollToBottom = () => { if (el.current !== null) el!.current!.scrollIntoView ...

What is the purpose of using square brackets in the angular.module() function in AngularJS?

const myapp=angular.module('myApp',[]); As someone venturing into the realm of angularjs, I have a question. What is the significance of using [] in angular.module()? If anyone could shed some light on this, it would be greatly appreciated. ...

Sort an array of strings using the qsort function and a comparison

Recently, I've been exploring the usage of qsort with an array of strings in my code. Here's a snippet of what I have so far: char words[500][256]; int numOfWords; // this value is determined earlier int sortWordList() { int length = sizeo ...

Tips on customizing autocomplete to display results fetched via ajax

I created a basic text box for users to input information. Using AJAX, I send this information to a PHP script to retrieve results. The results are then displayed in a DIV beneath the input box. However, I am struggling to update the autocomplete suggestio ...

Operating PhantomJS in server mode

I am considering using PhantomJS to convert a dynamic AngularJS application into static HTML that can be searched by Google. My plan is to set up a PhantomJS server behind a proxy to handle the ?escaped_fragment requests. While I know that PhantomJS is pri ...