explanation function with parameter e - javascript

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.

Related

Why do events have the “on” prefix in HTML?

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.

Simulate clicking a button

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.

Is it possible to force event listeners to fire in a particular order in JavaScript?

Is there a way to be notified or perform some callback function once an event has finished propagating in JavaScript?
Equivalently, and more specifically: is there a way to 'prioritize' an event and make sure that it is called after every other event listener has been fired (similarly almost to the !important value in CSS).
For instance, if I have 3 event listeners - 2 attached to the window and 1 to some button element. Can I force a certain one of those events to be called LAST, regardless of where it lies in the DOM? I understand that there are event phases and the ability to attach a listener to the capture or bubbling phase but this still means there's a preset order.
edit: the specific problem:
I'm attempting to build components (in React JS) which are aware of a click being registered outside of themselves (i.e. anywhere on the window/document except themselves) - often as a way of closing/hiding the component. Each of these components will register a listener on the window object which fires a function belonging to that component.
The trouble is, when another component [B] (inherently lower down in the DOM than the window) is clicked to let's say toggle the display of [A], [B]'s event fires first and toggles the state 'showA', the event bubbles up and [A]'s window event listener kicks in and re-toggles the state 'showA' - so, [A] remains hidden after changing state twice. I can't use stopPropagation as other window events need to fire. I've tried to unbind listeners but this doesn't happen in time.
An example of what currently happens all in one go is:
'show thing' button clicked
add listener to window for closing 'thing'
'window but not thing' was clicked
remove listener to close 'thing'
If only I could wait until the click event had finished bubbling before adding the new listener, I'd have no issue
I did leave an answer to your original question but I see you've updated it. I wouldn't say this is React specific but a common implementation for components that need to close/de-activate when the document is clicked.
For instance, the following snippet is an implementation for a speed dial spin out button;
(function () {
var VISIBLE_CLASS = 'is-showing-options',
btn = document.getElementById('.btn'),
ctn = document.getElementById('.ctn'),
showOpts = function(e) {
var processClick = function (evt) {
if (e !== evt) {
ctn.classList.remove(VISIBLE_CLASS);
ctn.IS_SHOWING = false;
document.removeEventListener('click', processClick);
}
};
if (!ctn.IS_SHOWING) {
ctn.IS_SHOWING = true;
ctn.classList.add(VISIBLE_CLASS);
document.addEventListener('click', processClick);
}
};
btn.addEventListener('click', showOpts);
}.call(this));
When the user clicks the button, the container is shown for the speed dial options and an event listener is bound to the document. However, you need to make sure that the initial event that is fired is not the one that triggers the takedown straight away (this is sometime a gotcha). This check is made with if (e !== evt) .... For further clicks the event check is made and the relevant action taken ending in removal of the event listener from the document.
Of course in your particular case if you want to only close when the element isn't clicked then you could make relevant checks on the evt.target and evt.currentTarget in the callback (in the snippet case, processClick).
Hopefully, this can help you out with registering close down callbacks for your individual components.

Why is event e undefined in callback when firing event manually?

I am using Mootools and adding a click event to a link. I have added a function to an event with this:
$('addCallRoute').addEvent('click', addCallRoute); // Add button
The function contains this:
function addCallRoute(e) {
console.log(e);
}
The function that fires the event (without an actual click)
$('addCallRoute').fireEvent('click');
The Problem:
When I click on the link physically, e is defined. but when I programmatically fire the event, e is undefined. Why?
Because you're not actually/physically triggering an action but firing it remotely. This is how it works.
event normally contains all sort of information about the element from which the action was triggered.
Always check if event is defined before trying to use any methods on it. Or do this:
link.fireEvent('click', {
stop: function(){}
});

JavaScript add an event listener any time and remove the event listener any time

In a web page I have a button when clicked it calls a JavaScript function.
In that function I show a modal dialog box and I want to process keystrokes only at this time. That is when the modal dialog is visible.
When I close the modal dialog I want to stop the keystroke processing.
consider that I click a button and function sam() is called.
function sam()
{
document.onkeypress = function(e) { processKeystroke(e); }
}
So now a function is attached to the keypress event. Whenever a key is pressed the function processkeystroke will be called.
The function sam is called only after I display the modal dialog box.
Now I am closing the modal dialog and with that I don't want function(e) { processKes...} to be called.
What should I do to remove the attached event listener from document.onkeypress.
Also I would like to have alternatives for the above approach because that one I assumed of my own and I did not refer any specific documentation, so I am really going through trial and error procedure to use event handlers or listeners.
So when I call function sam I want a function to be attached with the keypress event and if I call another function form example closedialog() I want that keypress listening function to be removed. Because I want to write proper code which should not consume lots of system resources.
Just write the following code to remove the handler.
document.onkeypress = null;
Since you are talking about attaching you maybe should check jquery which provides real bind (attach) and unbind (detach) for events like keypress.

Categories