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

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(){}
});

Related

Why the JS Event or CustomEvent doest not fire the first time on click after initial page load?

Im trying to figure out why the JS event doest not trigger for the first time after the page load.
Here is a simple way to reproduce the scenario
HTML
<button onclick="dispatch()">Test event</button>
JS
function dispatch() {
console.log('event');
const eventTest = new Event('navbar:test');
window.dispatchEvent(eventTest);
window.addEventListener('navbar:test', (e) => {
console.log('event was sent: ', e);
})
}
Live demo on codepen
Can someone pls explain the WHY of this behavior ? Is there a way to avoid this so that on the first click the event listener receive something using vanilla JS?
You're dispatching the navbar:test event before the event listener has actually been added for this event. It looks you may be expecting dispatchEvent() to fire the event asynchronously, but that is not what happens. The documentation says this:
Dispatches an Event at the specified EventTarget, (synchronously)
invoking the affected EventListeners in the appropriate order.
So just register the event listener before you dispatch the event:
window.addEventListener('navbar:test', (e) => {
console.log('event was sent: ', e);
})
window.dispatchEvent(eventTest);
As a sidenote, note that with the way your code is currently constructed, you are adding a new event listener for navbar:test every time you click the button - is this really what you want?
Problem is bubbling.
When you add event to window, it blocks another events inside window.
You should add option bubbles: true when you creates custom event.
like here
const eventTest = new Event('navbar:test', { bubbles: true });
* there also sometimes can be troubles when you touch button before script had been loaded and function dispatch had been saved into window object

explanation function with parameter e

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.

How can I intercept the tweet button click event?

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.

Trigger jQuery handler if search field contains "pre-populated" value

I have a search field that currently has an .on('input') event handler attached to it. However, in some instances the search field may be pre-populated if a value is passed through the URL (http://127.0.0.1/search/query-is-here). The issue here however is that the event handler will not be fired until the user edits the search field's value, meaning no search is automatically made.
I have tried initiating a .trigger by specifying focus, click, change, ... but none seem to work (and yes, I do change the event handler to .on('input focus') for example). What's the crack?
--
JS File (referenced in the footer BEFORE the trigger)
$('#search').on('input focus', function(e) {
e.preventDefault();
// various if statements and variable assignments
}
Trigger
// codeigniter -> http://ip.com/{segment 1}/{segment 2} -> this does get executed
<?php if($this->uri->segment(1) == "search" && $this->uri->segment(2)):?>
<script>
$('#search').focus();
$('#search').trigger("focus");
</script>
<?php endif; ?>
My understanding of $('#search').trigger("focus"); is that it should fire the event handler attached to #search, and execute the JS within that function.
You're subscribing to the event 'input focus' and triggering the event 'focus'. I think you'll want to subscribe to both events.
$('#search').on('focus', myHandler);
$('#search').on('focus input', myHandler);
Why are placing e.preventDefault() on focus? The event.preventDefault() method stops the default action of an element from happening.
Remove that e.preventDefault() from the code and try it again.
$('#search').on('input focus', function(e) {
//remvoe this line>> e.preventDefault();
// various if statements and variable assignments
}
Below is the jsfiddle link:
https://jsfiddle.net/shrawanlakhe/c8v5v788/1/
I have also place e.preventDefault() on the handler and it is preventing click event handler from firing .So first try it and the click event handler will not fire and then remove the e.preventDefault() and then try it again in the fiddle and this time event handler will fire

Event managment: Replace click event

I have a button with a click event (from a 3. party library) which submits a form. I like to remove the click event, add my own function and call the original event after a validation.
I thought i just add an event.stopImmediatePropagation(); but that did not work. Maybe because of the order the events where added(?).
Is the another way to manage the event execution?
Or how can I get the old event to do something like this:
originalClickEvent = $('#button').doSomeMagicAndGetTheEvent('click');
$('#button').unbind();
$('#button').bind('click', function (event) {
if (valid()) originalClickEvent();
});
Look here Remove all JavaScript event listeners of an element and its children?
After you remove the event listeners you can attach your custom event.
If I've understood you correctly this is the effect you're searching for: http://jsfiddle.net/ftGHq/
In case the click event is just bound to one function you could overwrite that function:
var oldFunction = theOldFunction;
function myFunction(control) {
oldFunction(control);
}
$('#button').unbind();
$('#button').click(myFunction);

Categories