Parameterized function call on click event

There is a function defined as follows:

menu[0].onclick = function() {
    filters.reset_all();
    clients.get();
}

This function gets called when the user clicks on the first menu element. Now, I need to invoke this function from another place and here's what I have done:

    if (li.onclick) { // li and menu[0] refer to the same element
        li.onclick.call();
    }

It works perfectly fine.

However, now I want to pass some parameters to the onclick function. I tried using .call(some_param); but the arguments array in the onclick function remains empty.

What am I missing?

edit: I made the following change:

menu[0].onclick = function(arg) {
    console.log(arg);
    filters.reset_all();
    clients.get();
}

and also

li.onclick.call(li, param);

but still no success.

Answer №1

When using .apply(), the initial argument serves as the this reference. The subsequent parameters are then passed to the function itself. If there is no need to explicitly specify the this context, you can directly call the function such as li.onclick().

In general, event handlers are invoked by the system and are supplied with the event object as the primary parameter. To accommodate functions that require varied arguments, it's advisable to create a separate function rather than altering the event handler. The event handler may call this custom function if needed.

menu[0].onclick = function() {
    myCustomFunc("alpha");
}

function myCustomFunc(arg) {
    // perform actions here
    filters.reset_all();
    clients.get();
}

if (li.onclick) {
    myCustomFunc("beta");
}

Answer №2

It is recommended to use the following syntax:

call(object, param1, param2, param3...);

If you are working on your specific scenario, you should write:

li.onclick.call(li, param1);

Answer №3

When using the call() method, the first parameter represents the context (referred to as this), while all subsequent parameters are placed into an arguments array in sequential order. On the other hand, if you opt for the apply() method instead of call(), you only need to provide two parameters: apply(this, arguments_array)

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

Angular 1.5 - Component for fetching HTML content with dynamic data

Help needed with using Angular Component method. Developing a main html file with its main controller containing a JSON list of client data: clients: [{ "name": "John Jackson", "age": "21", "hair": "brown", }, { "name": "Janet Doe", ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Managing the scrolling direction horizontally with waypoints.js

As I work on creating a custom wizard form with waypoints, I've encountered an interesting issue that has left me puzzled. In my sample CODEPEN, you can see two pages of the wizard process to better understand the problem. Upon clicking the forward ...

Implementing a switch feature with enable/disable functionality in a material table using table row data

Is there a way to incorporate an additional action in the Material table and have it included in the React material table along with the element? Furthermore, how can I obtain row data on onChange event while currently rendering it in the state? I would a ...

The absence of "_ssgManifest.js" and "_buildManifest.js" files in a Next.js application deployed on Google Cloud Platform was discovered

Upon opening the website, there are instances where the console displays the following errors: GET https://example.com/subpath/_next/static/9ufj5kFJf/_buildManifest.js [HTTP/3 404 Not Found 311ms] GET https://example.com/subpath/_next/static/9ufj5kFJf/_ss ...

What are the steps to integrate node-inspector with `npm start` in my application?

Currently, I am utilizing npm start to kickstart my MEAN stack application. However, I am interested in using the node-inspector to debug some Mongoose aspects. I am aware that the node inspector can be initiated with node-inspector, but I am unsure of wha ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

Tips for creating a functional null option using the select ng-options feature

While there are a few questions and answers on this topic, I have yet to find a solution that works for my specific case. Imagine having an object like this: $scope.person = {name: 'Peter', category1: null, category2: null}; Another variable r ...

Changes to attributes of an HTML tag cannot be made by jQuery code during an AJAX call

Could someone help me figure out why this jQuery code is not functioning properly? I have already tested it outside the $(document).ready block with no success. Note: The unusual "{{ }}" and "{% %}" syntax is typically used in Django. jQuery $(document) ...

Fill a form with jQuery and ajax data after it has been submitted

I'm working on a simple HTML form and I want to use Ajax to perform a lookup using a PHP file after entering data into the first field. The goal is to fetch information from an external source for the two remaining fields. <form method="post" acti ...

What is the best approach to updating multiple rows instead of just the first row using the update button located on both sides using PHP and AJAX?

Starting fresh, so I might sound like a beginner with this question. How can I make use of the update button to update specific rows instead of just the top row? Every time I try to update, it only works for the top row. Here's the code snippet from ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Is it possible to execute asynchronous queries within a map function in Mongoose?

Currently, I am struggling to create queries using a .map function, pushing the results to an array and then returning it. The issue is that the array always ends up empty due to the asynchronous nature of the operation. Although I attempted using async/ ...

What causes the appearance of a nested URL like '/auth/auth/ ' when the original URL does not exist?

While following a tutorial, I encountered an issue where if the URL is not included in the routes.ts file, it redirects to a nested /auth/auth/...../login/ instead of redirecting to localhost:3000/auth/login middleware.ts import authConfig from "./au ...

Solving repeated function firing with ng-checked in an AngularJS ng-repeat loop

In the HTML code below, there is an ng-repeat that creates checkboxes: <span ng-repeat="name in $ctrl.widgetSelectorNames" class="widget-selectors"> <label class="checkbox" for="{{name}}"> <input type="checkbox" value="{ ...

Utilize JavaScript to reference any numerical value

I am attempting to create a button that refreshes the page, but only functions on the root / page and any page starting with /page/* (where * can be any number). Below is the code I have written: $('.refresh a').click(function() { var pathNa ...

Display irregularly spaced time samples from a MySQL database on a Google Line Chart using a PHP query

Currently, I am utilizing a Line Chart from Google to display data fetched from a MySQL database involving various variables at different time intervals. Although the sample time is set at 1 minute, there are occasions where some data points are lost (for ...

Display information on the console from any location

I'm working on a Node.js project where I need to display text at specific locations, such as the top right corner. Is there a Node.js module available that can help me achieve this? Something like: var displayModule = require('display_module&ap ...

Is it possible to do bulk deletion in Flask Restless using AngularJS or JavaScript?

I am trying to implement bulk delete functionality in my AngularJS application by making an HTTP request to a Flask Restless API with version 0.17.0. While I know how to delete records one by one using their IDs in the URL, I am unsure if it is possible to ...