Why do events have the on prefix, like onclick, for example:
<button onclick="displayDate()">The time is?</button>
On W3Schools, it clearly states the onclick is an event, below is a screenshot:
But on MDN, it says that click is the event.
So my questions are:
Which one is the true event, onclick or click?
Why do we use onclick in HTML, but click in JavaScript, like this?
button.addEventListener('click', event => {
...;
});
Why not like this?
button.addEventListener('onclick', event => {
...;
});
which one is the true event, onclick or click?
click is the name of the event
onclick is the name of the property (and HTML attribute) to which you assign a function which will be called when the event is triggered
"on" is used in the sense "Indicating the day or part of a day during which an event takes place.": At the time the event takes place, the function is called.
why it is not
button.addEventListener('onclick',
The meaning "when the event is triggered" is conveyed by "addEventListener" so it doesn't need to be conveyed again by saying "on".
Also, some elements have methods like click() and focus() which make things happen. You'd get a name clash if the event handler properties had the same names.
Related
I have an element created dynamically, for which I have already attached an event listener to, like below:
radio.addEventListener('click', (event) => {
document.getElementById(action[1]).style.display = 'block';
});
The 'action[1]' is a string which will be the id of an element yet to be created. I have tried this, and it seems to work. I know the event listener's function will only be fired on the 'click' event, and by then the 'action[1]' element will exist. But it seems like I'm attaching an invalid function when the addEventListener is attached to my 'radio' element. Will this cause problems?
Okay, I want to close this with an answer, but the answer, comes from Barmar, so I don't take credit for it. As stated in the comment,
The body of a function isn't evaluated until the function is called.
There's no problem with access variables that are assigned between
adding the event listener and triggering the event.
Question is answered.
When I run both codes in the console, eventTarget.click() returns undefined but actually clicks the target element whereas eventTarget.dispatchEvent(new Event("click")) returns true but doesnt click the target element. I am trying to understand but I cant figure out why there are 2 different outcomes. Can you please explain why and how they are different? Arent both of them supposed to click the element on the page?
document.getElementById("button").click()
and
document.getElementById("button").dispatchEvent(new Event("click"))
The click() method is used to simulate a mouse click on the element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
The Event constructor is used to create a new event to be used on any element. The ‘click’ event can be passed to the constructor of Event to create a click event. This created Event has various properties which can be accessed to customize the event.
I will suggest using the MouseEvent instead of Event. Check below example
document.getElementById('eventTarget').click()
alert('before next')
document.getElementById('eventTarget').dispatchEvent(new MouseEvent("click"))
<input type="button" value="test" id="eventTarget" onclick="alert('clicked');"/>
I have this function copied from an exercise that I am trying to understand
loadEventListeners();
function loadEventListeners () {
cursos.addEventListener('click', addToCart);
}
function addToCart(e){
e.preventDefault();
console.log(e.target.classList);
}
I don't understand why it assigns the parameter "e" and then invokes it through e.target or because the preventDefault() is used
what the function does is return the list of classes on the button you click
e represents Event intefrace. The Event interface represents an event that takes place in the DOM. An event can be triggered by the user action e.g. clicking the mouse button or tapping keyboard.
Your function addToCart() triggered by user action, and e contains information about this event.
The preventDefault() method "cancels" the event, meaning that the default action that belongs to the event will not occur. For example, clicked anchors will not take the browser to a new URL.
Read more about the Event and preventDefault()
Whenever any event is triggered, a call function is called. In which event object is passed.
Event object contains every information related to event. Like on which button it is click, axis, attributes.
You can use this function for many purposes like finding parents, child, dimensions of the element and much more.
There are two function preventDefault and stopPropagation both used for different purposes.
preventDefault cancle default action that belongs to element like anchor element or so.
The stopPropagation() method prevents propagation of the same event from being called to child/ parents.
I'm developing a browser extension and I want to intercept the tweet button click event, just like in the image below:
I managed to get the element node like this:
document.querySelector('div[data-testid="tweetButton"]')
This is what I tried to do:
Override the node's "click" and "onclick" function
Override the node's "click" event listener, i.e. tweetButton.addEventListener("click", function() {})
Remove the "click" event listener, i.e. tweetButton.removeEventListener("click", function() {})
Repeat #1, #2 and #3 for "mousedown" and "onmousedown"
Add a global listener via document.addEventListener and check against a selector. The callback gets fired but the XHR still goes through, even if I did event.preventDefault() and event.stopImmediatePropagation().
Maybe it's not this object that the event listener is attached to, but in HTML it has the "button" role, so it should be the one.
Could I achieve the same goal by listening to the Ajax request?
After all, it seems solution #2 was correct:
let tweetButton = document.querySelector('div[data-testid="tweetButton"]');
tweetButton.addEventListener("click", function(event) {
event.preventDefault();
event.stopImmediatePropagation();
});
You can find here the open-sourced code.
If I have an existing click event associated with a button, can I use code to simulate that button being pressed so the code in the click event will run? I'm asking because I want there to be certain times where the user does not have to press the button for code to be executed. I would like to press the button automatically for them in certain instances if that makes any sense.
As simple as this,
$(function() {
$('#button').trigger('click');
});
var button = document.getElementById('yourButtonIdHere');
button.click();
This will fire a click event in the button
You can trigger a click event on an element by calling the .click() function on the element. By passing no value to the function the click event will fire, as opposed to setting up a listener for the click event.
If the button has an id of "form-btn", here's what that would like:
<button id="form-btn">Submit</button>
<script type="text/javascript">
//Setup the click event
$('#form-btn').on('click', function (e) {
alert('clicked!');
});
//Call the click event
$('#form-btn').click();
</script>
This should work fine, although I usually try to use a named function when setting up my event handlers, instead of anonymous functions. By doing so, rather than triggering the event I can call the function directly.
Note that in my experience, older browsers (IE6, IE7) sometimes limit what code-triggered events can do as a safety precaution for the user.
Here's documentation on the .click() function: http://www.w3schools.com/jquery/event_click.asp
Edit 1
I forgot that jQuery also has the .trigger() function, as used in choz's answer. That will also the job quite nicely as an alternative to .click(). What's nice about .trigger() is that it can trigger standard events as well as custom events, and also allow you to pass more data in your event.
Just make a function and run the function from within the button.
Three Choices:
You can call the click event handling function directly when appropriate:
if(timeIsRightForClick){
yourClickHandler();
}
You can simulate a button click by calling the .click() method of the button.
$("#ButtonID").click()
https://api.jquery.com/click/
Same as #2, but using jQuery's trigger() function, which can be used on standard events and custom ones:
$("#ButtonID").trigger("click");
http://api.jquery.com/trigger/
Choices #2 and #3 are usually better because they will cause the event handling function to receive a reference to the click event in case it needs to use that object. Choice #1 doesn't cause an actual click event (just runs the code you tell it to) and so no event object is created or passed to the event handler.