Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet.

What I need is the ID of the latest clicked button, so I tried this:

 var lastButtonId = [];//to store the latest Id
// then set up the onclick statements:
 document.getElementById('traffBut').onclick = sendButtonId('traffButton');
 document.getElementById('convBut').onclick = sendButtonId('convBut');
 document.getElementById('revBut').onclick = sendButtonId('revBut');
 document.getElementById('tranBut').onclick = sendButtonId('tranBut');
//Then here's the function to retrieve the last clicked ID:
 function sendButtonId (clickedButton)
       {
        lastButtonId.splice (0,1,clickedButton);   
         console.log(lastButtonId);
       }

However, when the page loads, the console displays this message: Click here to see console logs

I've tried various approaches to solve this issue but have been struggling with it,

Any hints or guidance would be greatly appreciated :)

Thanks in advance, J.

Answer №1

One reason why you need to pass a function to the onclick attribute instead of a function call is because you should provide a reference to the function to be called, not actually call the function at that moment.

If you want to execute the function sendButtonId when clicking on an element with the ID 'traffBut', simply do this:

document.getElementById('traffBut').onclick = sendButtonId;

However, if you need to pass arguments to the function when it's called, you can create a new function that automatically includes these arguments using .bind method, which generates a new function with specified parameters:

document.getElementById('traffBut').onclick = sendButtonId.bind(this, 'traffButton');

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

What is the process for removing a selection in V-autocomplete in Vuetify?

One of the features I implemented in my project is using Vuetify's v-autocomplete component. It allows users to search for and retrieve necessary information from an API. However, I encountered a scenario where I needed to delete the selection after t ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

What is the best way to update an array in TypeScript when the elements are of different types and the secondary array has a different type as

const usersData = [ { "id": 0, "name": "ABC" }, { "id": 1, "name": "XYZ" } ]; let dataList = []; // How can I transfer the data from the user array to the dataList array? // If I use the map function, do I need to initialize empty values for oth ...

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Using useState to initialize a long value

Obtaining a very large state from JSON can be challenging, especially when it consists of at least 50 lines. During page generation, an error like "there is no such value" may occur if the initial value is not set and the interface is not assigned properl ...

When function A invokes function B, function B reciprocates by calling function A. An ESLint error is raised, stating 'functionB' was utilized prior to its declaration

Imagine this scenario: a function called A is defined first and within it, function B is called; then function B is defined which in turn calls function A. The code looks like this: import { useState } from "react"; export default function App() ...

Encountered a 'File is not defined' error in JavaScript when running code from the node.js command line

I'm encountering an issue with my JavaScript code that is supposed to read a file and print it on the console. Despite having the file test.txt in the same path, I keep getting an error saying "File is not defined." Below is the snippet of the code: ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Display and conceal box using AngularJS checkboxes

I am currently facing some challenges in managing checkboxes and containers. The main objective is to have a list of checkboxes that are pre-selected. Each checkbox corresponds to a specific container, and when the checkbox is checked or unchecked, it shou ...

Customizing the main icon in the Windows 10 Action Center through a notification from Microsoft Edge

I am facing an issue with setting the top icon of a notification sent from a website in Microsoft Edge. Let's consider this code as an example: Notification.requestPermission(function (permission) { if (permission == "granted") { new ...

steps for retrieving final outcome from forkJoin

I am currently working with an array of userIds, such as: ['jd', 'abc']. My goal is to loop through these userIds and retrieve full names using an API. Ultimately, I aim to transform the initial array into [ {userId: 'jd', nam ...

Utilizing useEffect to retrieve and display an empty array in a React component

I am currently developing a React application that leverages Fetch to retrieve data from an API using SQLite. Strangely, when I check the console, it only displays a length of 3 and Array[0]. This means I can't access data based on specific IDs like I ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

When using the v-for directive to display all elements of an array, only the information of the clicked array should be listed when using the

I am facing an issue with my array of locations. There are 2 divs in play - one containing the list of locations and the other displaying additional info when a location is clicked. The problem arises when I click on a specific location, let's say Sc ...

Tips for verifying the presence of a Firestore Document reference within a JavaScript array of Document references

I am currently dealing with a document that contains an array field storing references to other documents. Upon fetching the document data and verifying if a document reference exists within the array, I consistently receive a result indicating that it is ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...

What is causing the Invalid left-hand side error in the postfix expression at this specific line of code?

I encountered an error stating "invalid left-hand side in postfix expression" while trying to execute this particular line of code data: 'Action=AutionMaxBid&AuctionItemID='+<?php echo $bidItemID ;?>+'', This error occurred d ...

Yeoman - Storing global settings efficiently

I have recently developed a Yeoman generator and am now looking to incorporate prompts for certain global configurations. My goal is to have the generator prompt users for their GitHub username and token during the initial run, and then somehow store this ...

Mask the "null" data in JSON

I'm currently working with a JSON file and trying to display it in a bootstrap table. Check out the code snippet I've been using: $(document).ready(function(){ $.getJSON(url, function(data){ content = '<h1><p class="p1 ...

Is it possible to assign a deconstructed array to a variable and then further deconstruct it?

Is there a way to deconstruct an array, assign it to a variable, and then pass the value to another deconstructed variable all in one line of code? Take a look at what I want to achieve below: const { prop } = [a] = chips.filter(x => x.id == 1); Typic ...