How to make a button link to JavaScript

Learn to create links using JavaScript, following the example: Add the HREF attribute and the default value to the button.

How to make a button link to JavaScript

Creating a button that links to a JavaScript function is easy and can be done using HTML and JavaScript. To do this, you will need to write an HTML element to create the button, and then attach an event listener to the button in JavaScript. This event listener will then execute the function when the button is clicked. Let's look at an example.


// HTML
<button type="button" id="myButton">Click Me</button>

// JavaScript
let myButton = document.getElementById("myButton");
myButton.addEventListener("click", myFunction);

function myFunction() {
  console.log("Button was clicked");
}

In this example, we first create an HTML element for the button, and give it an ID attribute. Then, in the JavaScript code, we use the document.getElementById() method to get a reference to the button, and add an event listener to it. This event listener will execute the myFunction function when it is clicked.

Once this is done, the button will be linked to the JavaScript function, and clicking the button will execute the myFunction function. This is a simple and straightforward way to link a button to a JavaScript function.

Answers (0)