- Html button with javascript function
- Button without a value
- Using buttons
- A simple button
- Adding keyboard shortcuts to buttons
- Disabling and enabling a button
- Setting the disabled attribute
- Inheriting the disabled state
- Validation
- Examples
- Technical summary
- Specifications
- How to use an HTML button to call a JavaScript function?
- Approach 1: Using the onclick event in JavaScript
- Syntax
- Example 1
- Approach 2: Using the ondblclick event in JavaScript
- Syntax
- Example 2
- Approach 3: Using the onclick event of an input button
- Syntax
- Example 3
- Approach 4: Using jQuery
- Syntax
- Example 4
- Conclusion
Html button with javascript function
An elements’ value attribute contains a string that is used as the button’s label.
input type="button" value="Click Me" />
Button without a value
If you don’t specify a value , you get an empty button:
Using buttons
A simple button
We’ll begin by creating a simple button with a click event handler that starts our machine (well, it toggles the value of the button and the text content of the following paragraph):
form> input type="button" value="Start machine" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
The script gets a reference to the HTMLInputElement object representing the in the DOM, saving this reference in the variable button . addEventListener() is then used to establish a function that will be run when click events occur on the button.
Adding keyboard shortcuts to buttons
Keyboard shortcuts, also known as access keys and keyboard equivalents, let the user trigger a button using a key or combination of keys on the keyboard. To add a keyboard shortcut to a button — just as you would with any for which it makes sense — you use the accesskey global attribute.
In this example, s is specified as the access key (you’ll need to press s plus the particular modifier keys for your browser/OS combination; see accesskey for a useful list of those).
form> input type="button" value="Start machine" accesskey="s" /> form> p>The machine is stopped.p>
const button = document.querySelector("input"); const paragraph = document.querySelector("p"); button.addEventListener("click", updateButton); function updateButton() if (button.value === "Start machine") button.value = "Stop machine"; paragraph.textContent = "The machine has started!"; > else button.value = "Start machine"; paragraph.textContent = "The machine is stopped."; > >
Note: The problem with the above example of course is that the user will not know what the access key is! In a real site, you’d have to provide this information in a way that doesn’t interfere with the site design (for example by providing an easily accessible link that points to information on what the site accesskeys are).
Disabling and enabling a button
To disable a button, specify the disabled global attribute on it, like so:
input type="button" value="Disable me" disabled />
Setting the disabled attribute
You can enable and disable buttons at run time by setting disabled to true or false . In this example our button starts off enabled, but if you press it, it is disabled using button.disabled = true . A setTimeout() function is then used to reset the button back to its enabled state after two seconds.
input type="button" value="Enabled" />
const button = document.querySelector("input"); button.addEventListener("click", disableButton); function disableButton() button.disabled = true; button.value = "Disabled"; setTimeout(() => button.disabled = false; button.value = "Enabled"; >, 2000); >
Inheriting the disabled state
If the disabled attribute isn’t specified, the button inherits its disabled state from its parent element. This makes it possible to enable and disable groups of elements all at once by enclosing them in a container such as a element, and then setting disabled on the container.
The example below shows this in action. This is very similar to the previous example, except that the disabled attribute is set on the when the first button is pressed — this causes all three buttons to be disabled until the two second timeout has passed.
fieldset> legend>Button grouplegend> input type="button" value="Button 1" /> input type="button" value="Button 2" /> input type="button" value="Button 3" /> fieldset>
const button = document.querySelector("input"); const fieldset = document.querySelector("fieldset"); button.addEventListener("click", disableButton); function disableButton() fieldset.disabled = true; setTimeout(() => fieldset.disabled = false; >, 2000); >
Note: Firefox will, unlike other browsers, by default, persist the dynamic disabled state of a across page loads. Use the autocomplete attribute to control this feature.
Validation
Buttons don’t participate in constraint validation; they have no real value to be constrained.
Examples
div class="toolbar"> input type="color" aria-label="select pen color" /> input type="range" min="2" max="50" value="30" aria-label="select pen size" />span class="output">30span> input type="button" value="Clear canvas" /> div> canvas class="myCanvas"> p>Add suitable fallback here.p> canvas>
body background: #ccc; margin: 0; overflow: hidden; > .toolbar background: #ccc; width: 150px; height: 75px; padding: 5px; > input[type="color"], input[type="button"] width: 90%; margin: 0 auto; display: block; > input[type="range"] width: 70%; > span position: relative; bottom: 5px; >
const canvas = document.querySelector(".myCanvas"); const width = (canvas.width = window.innerWidth); const height = (canvas.height = window.innerHeight - 85); const ctx = canvas.getContext("2d"); ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); const colorPicker = document.querySelector('input[type="color"]'); const sizePicker = document.querySelector('input[type="range"]'); const output = document.querySelector(".output"); const clearBtn = document.querySelector('input[type="button"]'); // covert degrees to radians function degToRad(degrees) return (degrees * Math.PI) / 180; > // update sizepicker output value sizePicker.oninput = () => output.textContent = sizePicker.value; >; // store mouse pointer coordinates, and whether the button is pressed let curX; let curY; let pressed = false; // update mouse pointer coordinates document.onmousemove = (e) => curX = e.pageX; curY = e.pageY; >; canvas.onmousedown = () => pressed = true; >; canvas.onmouseup = () => pressed = false; >; clearBtn.onclick = () => ctx.fillStyle = "rgb(0,0,0)"; ctx.fillRect(0, 0, width, height); >; function draw() if (pressed) ctx.fillStyle = colorPicker.value; ctx.beginPath(); ctx.arc( curX, curY - 85, sizePicker.value, degToRad(0), degToRad(360), false, ); ctx.fill(); > requestAnimationFrame(draw); > draw();
Technical summary
Specifications
How to use an HTML button to call a JavaScript function?
We use the onclick event attribute property of the HTML button to call a JavaScript function. The JavaScript code provided in the onclick attribute executes when the button is clicked. There are various attributes provided with the button tag in HTML that allows us to customize the button’s functionality and also let us decide how and what the button triggers.
Approach 1: Using the onclick event in JavaScript
The onclick event of the button element expects JavaScript code that is triggered when the button is clicked upon. So we put the function that needs to be called in the onclick property as well.
Syntax
This creates an HTML button with the name «click me» and triggers the «fun()» function.
Example 1
Here we will use an HTML button to call a JavaScript function. The associated function body executes when the button is clicked. Let’s look at the code for same.
!DOCTYPE html> html> title>Online Javascript Editor/title> head> /head> body> script> function fun() document.getElementById("result").innerHTML = "The function fun() is triggered !"; > /script> Calling js function using HTML button br>br> button onclick = "fun()"> click me !/button> p> div id = "result"> /div> /p> /body> /html>
In the above code, The function fun() is triggered when the button is clicked.
Approach 2: Using the ondblclick event in JavaScript
More options are provided to customize the execution of the JavaScript functions in different ways. for example, we can also set the function to be called only when the button is double-clicked. This can be done with the «ondblclick» event of the button tag.
Syntax
This creates an HTML button with the name «Button_Name» and triggers the «fun()» function when the button is double-clicked.
Example 2
Here we will use an HTML button to call a JavaScript function. The associated function body executes when the button is double-clicked.
!DOCTYPE html> html> title>Online Javascript Editor/title> head> /head> body> script> function fun() document.getElementById("result").innerHTML = "The function fun() is triggered !"; > /script> h3>Calling js function using HTML button br>/h3> p> Double click "click me!" button /p> button ondblclick = "fun()"> click me ! /button> p> div id = "result"> /div> /p> /body> /html>
In the above code, we have the «click me» button that triggers the fun() function when it is double clicked.
Approach 3: Using the onclick event of an input button
Buttons can also be part of forms that do some sort of validation and form submission. Buttons can also be created using the input tag provided by HTML. The onclick event attribute is again configured to handle the behavior of the button.
Syntax
This creates an HTML button with the name «Button_Name» and triggers the «fun()» function.
Let us look at an example to see this use case.
Example 3
We will create a button for submitting a mock form, this button triggers the JavaScript function provided in the onclick property.
!DOCTYPE html> html> title>Online Javascript Editor/title> head> /head> body> script> function fun() document.getElementById("result").innerHTML = "The function fun() is triggered !"; > /script> Calling js function using HTML button br>br> form> label> Name : /label> input type = "text"> /input>br>br> input type = "button" onclick = "fun()" value = "submit"> /form> p> div id = "result"> /div> /p> /body> /html>
In the above code, The function fun() is triggered when the submit button is clicked.
Approach 4: Using jQuery
As an alternative we can also use jQuery to attach the function to the button programmatically.
Syntax
This jQuery script checks for the readiness of the document and then attaches the function fun() to the click of the button having id as «Your_Button».
Let us look at an example to see this use case.
Example 4
We will create a HTML button and attach an event handler «onclick» to it programmatically using jQuery. Note that this attachment happens after the complete document has been rendered successfully.
The script in head tag imports the jQuery.
!DOCTYPE html> html> title>Online Javascript Editor/title> head> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">/script> /head> body> Calling js function using HTML button br>br> button id="button"> click me !/button> p> div id="result"> /div> /p> script> $(document).ready(function() $('#button').click(function() fun(); >); >); function fun() document.getElementById("result").innerHTML = "The function fun() is triggered !"; > /script> /body> /html>
Conclusion
The onclick property of HTML buttons are a fast and effective way of attaching JavaScript functions to them.