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);
Related
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.
I have the following line in my page:
<div id="fmeFriendStatus" style="width:589px;height:700px;overflow:auto" onmouseover="DelayedStatusRefresh()">
I want to be able to change:
onmouseover="DelayedStatusRefesh()"
command to:
onmouseover="DelayedStatusRefeshFriends()"
by clicking on a button elsewhere on the page...
Is this possible and how would you do it?
Many thanks in advance
The quick answer is as follows:
var button = document.getElementById('someButtonId');
button.addEventListener('click', function() {
document.getElementById('fmeFriendStatus').onmouseover = DelayedStatusRefeshFriends;
});
However, directly accessing onclick or other on* properties to listen for events is frowned upon for numerous reasons. Ideally, you would add DelayedStatusRefesh as an event listener using addEventListener() (or maybe using a JavaScript library, like jQuery), and when the button is clicked, remove that listener (removeEventListener()) and add the other.
You need to add the onclick handler to the second button, and its handler needs to reassign the mouseover handler for the fmeFriendStatus element.
So it should be something like this:
document.getElementById("buttonFromSomewhereElse").onclick = function() {
document.getElementById("fmeFriendStatus").onmouseover = DelayedStatusRefeshFriends;
}
Let's suppose there is an <img> element that has some onclick event handler. For example onclick it does alert("OldEventHandler").
I would like to add my event handler there, before the existing one. For example my event handler function does alert("NewEventHandler").
So on click I would like to see "NewEventHandler" popup, and then "OldEventHandler" popup.
This needs to be implemented in pure JavaScript; no jQuery Please.
You can save the original handler, then call it after yours is done:
var oldHandler = myElement.onclick;
myElement.onclick = function() {
// do your stuff here
...
// then call the original
oldHandler.apply(this, arguments);
}
Another approach to this problem would be to create a generic event handler that stores an array of functions in some predefined order. When the onclick() event is fired, you can call the functions you need in that order.
Is it possible to remove than add back click event to specific element? i.e
I have a $("#elem").click(function{//some behaviour});, $(".elem").click(function{//some behaviour});(there are more than 1 element) while my other function getJson is executing I'd like to remove the click event from the #elem, and add it again onsuccess from getJson function, but preserve both mouseenter and mouseleave events the whole time?
Or maybe create overlay to prevent clicking like in modal windows? is that better idea?
edit :
I've seen some really good answers, but there is one detail that I omitted not on purpose. There are more than one element, and I call the click function on the className not on elementId as I stated in the original question
Rather than using unbind(), which means you'll have to rebind the same event handler later, you can use jQuery's data() facility with the ajaxStart and ajaxStop events to have your elements ignore click events during all AJAX requests:
$(".elem").click(function() {
if (!$(this).data("ajaxRequestPending")) {
// some behaviour
}
}).ajaxStart(function() {
$(this).data("ajaxRequestPending", true);
}).ajaxStop(function() {
$(this).removeData("ajaxRequestPending");
});
EDIT: This answer is also id-to-class-proof (see questioner's edit), since everything matching the selector will handle the AJAX events the right way. That's the main selling point of jQuery, and it shows.
You are looking for .unbind(). Pass it 'click' and it will destroy the click event.
I would put it just before your getJSON and re-bind the click event inside the success handler of your ajax call.
You have to do some additional scripting. There is no callback for that. Take a look over here: jQuery - How can I temporarily disable the onclick event listener after the event has been fired?
Rather than unbinding/binding the click event, you could check the state of another variable to see if it should do the action.
var MyObject = {
requestActive = false;
};
function MyJsonFunction() {
// when requesting
MyObject.requestActive = true;
//...
// when request over
MyObject.requestActive = false;
}
$("#elem").click(function{
if (MyObject.requestActive == true) {
//do something
}
});
I have an ajax app that will run functions on every interaction. I'd like to be able to run my setup function each time so all my setup code for that function remains encapsulated. However, binding elements more than once means that the handler will run more than once, which is obviously undesirable. Is there an elegant way in jQuery to call bind on an element more than once without the handler being called more than once?
User jQuery one function like Tom said, but unbind the handler each time before binding again. It helps to have the event handler assigned to a variable than using an anonymous function.
var handler = function(e) { // stuff };
$('#element').unbind('click', handler).one('click', handler);
//elsewhere
$('#element').unbind('click', handler).one('click', handler);
You can also do .unbind('click') to remove all click handlers attached to an element.
You could attach the event to document with the one() function:
$(document).one('click', function(e) {
// initialization here
});
Once run, this event handler is removed again so that it will not run again. However, if you need the initialization to run before the click event of some other element, we will have to think of something else. Using mousedown instead of click might work then, as the mousedown event is fired before the click event.
You can also use .off() if unbind doesn't do the trick. Make sure the selector and event given to .off exactly match the ones initially provided to .on():
$("div.selector").off("click", "a.another_selector");
$("div.selector").on("click", "a.another_selector", function(e){
This is what worked for me in resolving the same ajax reloading problem.
The answer from Chetan Sastry is what you want. Basically just call a $(element).unbind(event); before every event.
So if you have a function like loadAllButtonClicks() that contains all the
$(element).on("click", function (){});
methods for each button on your page, and you run that every time a button is clicked, this will obviously produce more than one event for each button. To solve this just add
$(element).unbind(event);
before every
$(element).on("click", function (){});
and it will unbind all events to that element, then add the one click event.