xxxxxxxxxx
// Here you can use getElementById
// or getElementByClassName or getElementByTagName...
// Example #1
document.getElementById("button").onclick = function() {
alert("Hello World!");
}
// Example #2
let obj = document.getElementsByClassName('button');
obj.addEventListener("click", function() {
// your code here...
});
// Example #3 (getting attributes)
let obj = document.getElementById("button")
obj.onclick = function() {
obj.style.display = "none";
// or:
// obj.style = "display: none; color: #fff"
}
xxxxxxxxxx
var button = document.querySelector('button');
button.onclick = function() {
//do stuff
}
xxxxxxxxxx
// Get the HTML element with the id "myButton"
const button = document.getElementById("myButton");
// Add click event listener to the button
button.addEventListener("click", function() {
// Code to be executed when the button is clicked
console.log("Button clicked!");
});
xxxxxxxxxx
/*
The onclick event generally occurs when the user clicks on an element.
It allows the programmer to execute a JavaScript's function when an element
gets clicked
*/
<!DOCTYPE html>
<html>
<head>
<script>
function fun() {
alert("Welcome to the javaTpoint.com");
}
</script>
</head>
<body>
<h3> This is an example of using onclick attribute in HTML. </h3>
<p> Click the following button to see the effect. </p>
<button onclick = "fun()">Click me</button>
</body>
</html>
xxxxxxxxxx
// Select an element with the specified ID
const button = document.getElementById('myButton');
// Add an onclick event handler to the selected element
button.onclick = function() {
alert('Button clicked!');
};
xxxxxxxxxx
// Select the element using its ID
var element = document.getElementById('myButton');
// Add the onclick event listener
element.onclick = function() {
// Code to be executed when the element is clicked
console.log('Button clicked!');
};
xxxxxxxxxx
<script>
function activateLasers () {
//... your code to activate the lasers
console.log ("Lasers Activated")
}
</script>
<button onclick="activateLasers()">
Activate Lasers
</button>
xxxxxxxxxx
function handleClick() {
// Code to be executed when the element is clicked
console.log("Clicked!");
}
// Add click event listener to an element with id "myElement"
document.getElementById("myElement").onclick = handleClick;
xxxxxxxxxx
function functieBijEvent()
{
alert("Je klikte!");
}
function maakEvents()
{
// Events voor de HTML-elementen aanmaken:
document.getElementById("knop").onclick = functieBijEvent;
}
window.onload = maakEvents; // Functie maakEvents() wordt aangeroepen als window.onload getriggerd wordt
// In die functie worden de rest van de events toegekend aan hun HTML-elementen
// Omdat window.onload pas getriggerd wordt als alles geladen is bestaan alle HTML-elementen al