Jul 18, 2024
onclick="alert('1')"
)addEventListener
method for better code organizationCreate a button in HTML:
<button class="btn btn-primary btn-block" id="button">Click Here</button>
Set up event listener in JavaScript:
const button = document.getElementById('button');
button.addEventListener('click', function() {
console.log('Button clicked');
});
document.getElementById('header-title').textContent = 'Changed';
document.querySelector('#main').style.backgroundColor = 'lightgray';
e
e.target
– the element that triggered the evente.type
– the type of evente.clientX
, e.clientY
– mouse position relative to the browser windowe.offsetX
, e.offsetY
– mouse position relative to the elemente.altKey
, e.ctrlKey
, e.shiftKey
– check if these keys are held downbutton.addEventListener('click', function(e) {
console.log(e.target.id); // Logs the ID of the clicked element
console.log(e.type); // Logs the type of event
});
const output = document.getElementById('output');
output.innerHTML = `<h3>${e.target.id}</h3>`;
click
: Fires when an element is clickeddblclick
: Fires on double clickmousedown
: Fires when the mouse button is pressed downmouseup
: Fires when the mouse button is releasedconst div = document.getElementById('box');
div.addEventListener('mouseenter', ...);
div.addEventListener('mouseleave', ...);
const input = document.querySelector('input[type="text"]');
input.addEventListener('keydown', ...);
input.addEventListener('keyup', ...);
input.addEventListener('keypress', ...);
focus
: Fires when an element receives focusblur
: Fires when an element loses focusinput.addEventListener('focus', runEvent);
input.addEventListener('blur', runEvent);
input.addEventListener('cut', runEvent);
input.addEventListener('paste', runEvent);
Handling form submission
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
e.preventDefault(); // Prevents page reload
runEvent(e);
});
Handling change event in a select box
const select = document.querySelector('select');
select.addEventListener('change', function(e) {
console.log(e.target.value); // Logs the selected option value
});
addEventListener
for better code organization[End of Transcript]