I'm trying to get the event associated with an element and try to trigger the respective event. For example if I pass an id for a textbox and it has an event focus binded with it, then I want to trigger that focus event. I know we can get the event details by using
$.data('selector', 'events');
but how to use this object? This should be in jquery or javascript.
Thanks in advance
Not sure why on Earth would you need this. Try triggerHandler
var item = $("selector"),
trigger = function(name){
item.triggerHandler(name);
};
$.each($.data(item[0], "events"), trigger);
Warning This code won't work with delegated events and such. It only triggers handlers bound to matched element.
Related
So I'm modifying a webpage, it has a button, it is coded so mouseup goes to a link, I want to change this, adding mouseup functions don't work; mousedown works but I have to hold the mousedown for a second or two otherwise the original function still occurs.
var duma = $('input')[0].value;
var siq = $('.inline-nav-menu__link')[1];
$(siq).mousedown(function(){
window.location = 'https://www.google.com/search?q='+duma+'&sxsrf=APq-WBtOrInsFht_VAH6gWFlCceGK46ylQ:1649149133894&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjdvbqix_z2AhWtxzgGHW7GCh0Q_AUoAXoECAIQAw&biw=1366&bih=696&dpr=1';
})
This works but I have to keep the mouse held down for a lil bit
Changing that to mouseup doesn't work
I inspected the element further, it had an attribute named formAction which had the link to the respective page. Changing said attribute solved the first problem. But now the page is going to google web instead of images...
var duma = $('input')[0].value;
var siq = $('.inline-nav-menu__link')[1];
$(siq)[0].formAction='https://www.google.com/search?tbm=isch&q='+duma+'';
When you add an event listener, you're creating a function (that is a Javascript object) and binding it to a specific event.
To remove the listener, you have to pass to .removeEventListener() a reference to that same function.
Working with jQuery, there's also the element.off('event_type') method, but it works only on listeners previously attached with the jQuery .on('event_type') method.
If the listener refers to a named function you can do element.removeEventListener('event', functionName).
If the listener is an anonymous function I'd do one of these:
A) clone the element with jQuery clone() method, so that the cloned element will not have any event listeners attached anymore. Then you could attach your own listeners.
B) if you don't need the original event listener, you can also disable it doing like this:
function stopEvent(event) {
event.stopImmediatePropagation();
}
element.addEventListener('mouseup', stopEvent, true);
This way, using the true option in .addEventListener, you stop any event propagation at the beginning of the capturing phase, so the event itself will never reach its target (for that mouseup event only).
The cons of the second option is that you cannot use that event anymore on that element, as it will never reach the target.
But, as you used a named function to stop the propagation, you can now remove it with element.removeEventListener('mouseup', stopEvent, true) and bring back the original event listener to work again (because removing stopEvent, now the event propagates again to its target).
Figured it out. Needed to change form values.
Used the info on google search forms from link.
https://stackoverflow.com/a/65032682/10824788
var duma = $('input')[0].value;
var siq = $('.inline-nav-menu__link')[1];
var derka = 'https://www.google.com/search?tbm=isch&';
$(siq)[0].form[2].name="q";
$(siq)[0].form[2].value=duma;
$(siq)[0].form[4].name="tbm"
$(siq)[0].form[4].value="isch"
$(siq)[0].formAction=derka;
I'm trying to remove an already existing event listener from an object. I've tried several methods (using jQuery .off(), .unbind(), standard removeEventsListeners()), but as stated in the docs they can only remove previously added ones?
Using the Chrome debugger, I can see and remove the specified event listener,
Also, when trying to list the event listeners via jQuery _data() function, it won't list the event. Have been searching for an answer for a couple of hours now.
Can anyone help? Any workaround?
Edit: I have to keep some, so cloning is not possible.
If the event handler was added with addEventListener, you cannot remove it unless you have a reference to the handler function that was added. I assume that must be the case, because if it were hooked up with jQuery's on (or various shortcuts for it), off would work, and you've said it didn't work.
One way to work around that is to replace the element with a clone. When you clone an element using the DOM's cloneNode, you don't copy its event handlers. So if you start out with element, then you can clone it, use insertBefore to insert the clone, then use removeChild to remove the original:
var newElement = element.cloneNode(true); // true = deep
element.parentNode.insertBefore(newElement, element);
element.parentNode.removeChild(element);
Of course, this is indeed a workaround. The proper thing would be not to set up the handler in the first place, or keep a reference to it if you need to be able to remove it later.
In a comment you've said you can't do that, and asked:
Is there a way to add a new event listener that blocks the already existing one?
Only if you can get there first, otherwise no, you can't.
You can't add a new handler that blocks an existing one (not in a standard way cross-browser), but if you can add yours before the other one is added, you can prevent it being called by using stopImmediatePropagation:
// Your handler
document.getElementById("target").addEventListener("click", function(e) {
console.log("Your handler");
e.stopImmediatePropagation();
e.stopPropagation();
});
// The one that you're trying to prevent
document.getElementById("target").addEventListener("click", function(e) {
console.log("Handler you're trying to prevent");
});
<div id="target">Click me</div>
So for instance, if the other handler is added in the window load event, or a jQuery ready handler, you may be able to get yours in first by putting your code in a script tag immediately after the element in question.
A very easy way of doing this is to append nothing to the parent element with .innerHTML. Just be aware this destroys all event listeners that are descendants of the parent element. Here's an example (click 2 to destroy the event listener attached to 1):
const d1 = document.querySelector('#d1');
d1.addEventListener('click', () => console.log(123));
const d2 = document.querySelector('#d2');
d2.addEventListener('click', () => d1.parentNode.innerHTML += '');
<div><button id="d1">1</button></div>
<div><button id="d2">2</button></div>
I need to attach a JavaScript click listener to an add new record confirmation on a DevExpress gridview.
I can't use a regular click event listener as it's loaded via AJAX integrated into the control. I also have no access to the button's code so am unable to extend it.The only thing I do have is the button name.
Ideally I want to listen for the appearance of the button on the DOM and then attach the listener, is there any way to do this?
You do not need to wait for the appearance of the button in the DOM.
Just use a delegated event handler attached to a non-changing ancestor of the dynamic elements.
e.g.
$(document).on('click', '.someclass', function(){
///
});
If you only have the element name for the button use an attribute selector:
e.g.
$(document).on('click', '[name="somename"]', function(){
///
});
Delegated events work by listening for events bubbling up to a non-changing ancestor (document is the default if nothing closer is available). It then applies the selector at event time (not at event registration time). It then calls the function for any matching element that caused the event.
The end result is that it will work with elements that may exist later, when the event occurs.
Note: if nothing is closer to the dynamic content, use document, but do not use 'body' as styling can make it have a zero height and delegated mouse events will not work!
Is it possible to trigger an event on some object with a custom event object?
i.e.
$('#Element1').click(function(event){
console.log('Element1 clicked', event);
}
$('#Element2').click(function(event)
{ //handle click on one element
//optionally modify the event object
event.target=Something;
//Trigger the event handler(s) on some other element using modified event object
$('#Element1').click(event);
});
A bit of background:
In my instance Element2 is an almost identical clone of Element1 but with different position. When Element2 is clicked that click should be forwarded to Element1.
I already have code to identify the correct child of Element1 according to which child of Element2 was clicked but the click event handler on the child of element 1 requires the pageX and pageY properties to be set correctly and .click() omits these properties entirely.
It does not suffice in my example to do a deep clone and include the event handlers because the target property is incorrectly set.
One workaround in my instance would be for the cloned element to retain a reference to the original element (and for every child) and the handler to check for that reference, however, I would prefer a solution where the handler has no knowledge of the cloning process - not least because there are a LOT of handlers to modify!
I am not understand well your background logic, but you can try with trigger from jQuery. You can trigger event reusing the event object:
$('#Element1').click(function(event){
console.log('Element1 clicked with changed event: ' + event.something);
});
$('#Element2').click(function(event){
event.something = "Something";
$('#Element1').trigger(event);
});
You can try with .trigger() it accepts an event object as the argument
$('#Element1').trigger(event);
Demo: Fiddle
I'm trying to trigger my own custom events as global events, so that anything on my page can listen to them and react, however, for dynamically added content it's not working. See my fiddle at: http://jsfiddle.net/6TMkG/8/
As far as I understand, the event is triggered for any element in the page that jQuery knows has a handler for it, and it seems it doesn't trigger the event for the li's even though they do have a handler.
Anyone know how to get around this behaviour?
try this
$("#b2").click(function() {
//$.event.trigger("randomEvent");
$('li').trigger('randomEvent');
});
If you want global event, then you could bind the event handler on document, and trigger it on any element in the document.
$(document).on('randomEvent', callback);
$('ul').click(function() {
$(this).trigger("randomEvent");
});
Sorry I completely missed that.. I did not see the first part of your question.. Custom events.. Looks like you are associating the randomEvent but you are not triggering that event when that is associated with it..
Make sure you add the trigger Event in the Document.Ready function so that the evnet handler is associated with as and when the element is available.