Tips for implementing an `onclick` event on this specific button

I've utilized JavaScript to generate a button. Now, I'm wondering how to incorporate an onclick event for this button.

var b1 = document.createElement("button");
b1.setAttribute("class", "btn btn-default");
b1.setAttribute("id", "viewdetails");
b1.innerHTML = "View Details";
d3.appendChild(b1);  

Answer №1

If you want to include a function in the click listener, you can utilize HTMLElement#addEventListener():

let button = document.createElement("button");
button.setAttribute("class", "btn btn-default");
button.setAttribute("id", "viewdetails");
button.innerHTML = "View Details";
button.addEventListener("click", function() {/* add your code here */});
container.appendChild(button);

Answer №2

Here's an alternative method to achieve this: (Using Scath's Snippet)

Implementing the onclick attribute

var button = document.createElement("button");
var container = document.getElementById("container");
button.setAttribute("class", "btn btn-default");
button.setAttribute("id", "viewdetails");
button.setAttribute("onclick", "handleClick();")
button.innerHTML = "View Details";
container.appendChild(button); 
   

function handleClick(){
console.log("Button clicked")
}
.btn{

}
<div id="container"></div>

Answer №3

Executing the code below will trigger the function func.

var button1 = document.createElement("button");
var container = document.getElementById("container");
button1.setAttribute("class", "btn btn-default");
button1.setAttribute("id", "showdetails");
button1.innerHTML = "Show Details";
container.appendChild(button1);  
button1.addEventListener("click", func)

function func(){
console.log("clicked")
}
.btn{

}
<div id="container"></div>

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

Obtaining the blog slug dynamically upon clicking with ReactJS

Currently, I am developing a project using Reactjs and Nextjs. One of the tasks at hand is to obtain the "slug" value after clicking on a blog post. However, at this moment, the value returned is undefined despite trying the following code: <h4 onClic ...

What is the best method for interpreting XML using JavaScript?

I am facing a challenge with fetching and parsing an XML file using JavaScript. The XML-file is beyond my control. Recently, there has been a change in the encoding of some XML files which prevents the code from being parsed successfully. Previously it wa ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Having trouble displaying a background image on a React application

Public>images>img-2.jpg src>components>pages>Services.js> import React from 'react'; import '../../App.css'; export default function Services() { return <h1 className='services ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Is there a way to efficiently modify the positions of numerous markers on Google Maps while utilizing PhoneGap?

Hey there, I'm new to this and I have a service for tracking multiple cars. I'm using a timer to receive their locations, but I'm having trouble figuring out how to update the old marker with the new value. I've tried deleting all the m ...

Why is 'this.contains' not recognized as a function when I invoke it within another function?

While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could thi ...

What is the best way to ensure the initial item in an accordion group remains open by default when using NextJS?

I've successfully developed an accordion feature in NextJS from scratch and it's functioning flawlessly. However, I am looking to have the first item of the accordion open automatically when the page loads. Can anyone guide me on how to make this ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

The "Overall Quantity" of items will vary as it goes through different numerical values, despite the fact that I employed --

I am currently working on an e-commerce website with a shopping cart feature. The cart displays the number of items added to it, which increases by one when 'Add to Cart' is clicked and decreases by one when 'Remove' is clicked. However ...

Issues with Mocha's beforeEach() and done() functions not functioning as expected

I am facing an issue with my Mocha test suite. When I run the 'make test' command, I encounter the following error message: Uncaught TypeError: Object [object Object],[object Object] has no method 'done' Below is the relevant code sni ...

What is the best way to change a JSON string into an array of mysterious objects?

I am currently working on a flashcard generator project and I am dealing with a JSON String that is quite complex. The JSON String contains multiple arrays and objects structured like this: data = [{"front":"What is your name?","back":"Billy"},{"front":"H ...

Vue.js does not support sorting columns

In this specific codepen example, I have created a Vue table that allows for sorting by clicking on the column name. Although I can successfully retrieve the column name in the function and log it to the console, the columns are not sorting as expected. Wh ...

Unveiling the solution: Hide selected options in the input field of Material UI Autocomplete in React

I need help with not displaying the labels of selected options in the input field. I think it might be possible to do this using the renderInput property, but I'm not sure how. Even with the limitTags prop, the options still show up in the input field ...

The negative z-index is causing issues with my ability to select classes using jQuery

By setting a z-index of -3 for several divs in my background, I thought they wouldn't affect the formatting of elements in the foreground. But now I'm facing an issue where I can't click on those background divs when trying to target them wi ...

Exploring the power of VueJs through chaining actions and promises

Within my component, I have two actions set to trigger upon mounting. These actions individually fetch data from the backend and require calling mutations. The issue arises when the second mutation is dependent on the result of the first call. It's cr ...

JavaScript code to remove everything in a string after the last occurrence of a certain

I have been working on a JavaScript function to cut strings into 140 characters, ensuring that words are not broken in the process. Now, I also want the text to make more sense by checking for certain characters (like ., ,, :, ;) and if the string is bet ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem https://i.sstatic.net/VreXd.png The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show ...

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

Ordering Algorithm in AJAX Grid

I have a specific requirement that I spotted on this website: Whenever a user clicks on the table header, the content should be sorted accordingly. I have successfully implemented this feature for tables with pre-set values. https://i.sstatic.net/7cebx.p ...