Call javascript function from html Code Example

Last Updated On Saturday 4th Dec 2021

Using an HTML button to call a JavaScript function

Defining in HTML

	<input id="tapMe" type="button" value="tapme" onclick="doFunction();" />
	

Adding it to the DOM property for the event in Javascript

	document.getElementById("tapMe").onclick = doFunction;

document.getElementById("tapMe").onclick = function () { alert('You Successfully Tap ME!'); };
	

Here’s the small Example

  • Attaching a function to the event handler using Javascript
	<ul>
  <li class="red button">Red Button</li>
  <li class="blue button">Blue Button</li>
  <li class="green button">Green Button</li>
</ul>
	
	const list = document.querySelector("ul");

list.addEventListener("click", (e) => {
  e.target.style.fontSize = "24px";
  if (e.target.classList.contains("red")) {
    e.target.style.color = "red";
  }
  if (e.target.classList.contains("blue")) {
    e.target.style.color = "blue";
  }
  if (e.target.classList.contains("green")) {
    e.target.style.color = "green";
  }
});