JSFiddle - React, Tailwind, and code Playground
Best Practice Button
by LW
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<button id="my-btn">Best Practice Button!</button>
<form>
<input type="submit" onclick="return bar()" value="Worst Practice Button!">
<input id="submit2" type="submit" value="This ought to be a button, not input!">
</form>
</body>
</html>
CSS
button, input {
display: block;
margin: 20px;
}
JavaScript
//get the element reference
var myBtn = document.getElementById('my-btn');
//this will make the button call function "foo" when it is clicked.
myBtn.addEventListener('click', foo);
//the "event" object is automatically passed to the event handler
function foo(event) {
console.log('Foo!');
}
function bar() {
console.log('Bar!');
return false;
}
var submit2 = document.getElementById('submit2');
submit2.addEventListener('click', baz);
function baz(event) {
event.preventDefault();
console.log('Baz!');
}