Append my Event handler before existing handler - javascript

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.

Related

jQuery remove event handler which is specified in the View

My understanding is that when using the unbind and off jQuery methods, I should be able to remove an event handler from an element as follows
The textbox created in the view, with an onkeypress event handler applied
#Html.TextBoxFor(Function(m) m.sometext, New With {.onkeypress = "eventhandler();", .id = "theID"}
The JavaScript which is trying to remove the event
function eventhandler()
{
alert("should only hit once");
// this doesnt unbind the event
$("#theID").unbind("onkeypress");
// Nor does
$("#theID").off();
//???
}
My thinking could be that the unbind only works with bind and the off only works when on is used. I say this as the jQuery API website states
The .off() method removes event handlers that were attached with .on()
If this is the case, can I not apply the handler in the view at all?
I'd like to add I want to do this in the view and I want to apply a unique ID which is from the ViewModel
Any help would be helpful
Thanks
You can use either removeAttr()
$('#theID').removeAttr('onkeypress');
or set the event handler to null
$('#theID'')[0].onkeypress = null;

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);

need help understanding this code

this code in book jQuery in action page 131
i don't understand
.trigger('adjustName');
what is adjustName
and Simple explanation for trigger()
thanks :)
$('#addFilterButton').click( function() {
var filterItem = $('<div>')
.addClass('filterItem')
.appendTo('#filterPane')
.data('suffix','.' + (filterCount++));
$('div.template.filterChooser')
.children().clone().appendTo(filterItem)
.trigger('adjustName');
});
It is a string, the name of a custom event you defined.
E.g. it would trigger the event handler bound by:
el.bind('adjustName', function(){...});
For more information I suggest to have a look at the documentation:
Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user.
Without knowing the context of the code, I would say that calling .trigger() here has no effect, as it is called on the cloneed elements and the event handlers are only cloned if true is passed to clone.
Maybe the original jQuery manual could be helpful?
Description: Execute all handlers and
behaviors attached to the matched
elements for the given event type.
It allows you to trigger, or run, an event. For instance if you wanted the code to mimic the clicking of a button, you could write....
$("#myButton").trigger('click');
This would then run exactly as if you had clicked the button yourself.
'adjustName' is a custom event. So the trigger function is running that custom event. The custom event is assigned using the jQuery bind function.
$("#someElement").bind('adjustName', function() {/* Some Code */});
You might create a customer event for clarity. Perhaps your application opens a document, so you might want an event called 'openDocument' and 'closeDocument' assigned to the element containing the document.

In jQuery, is there any way to only bind a click once?

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.

Intercept javascript event

Here's what I'm trying to do :
I have a page with some links. Most links have a function attached to them on the onclick event.
Now, I want to set a css class to some links and then whenever one of the links is clicked I want to execute a certain function - after it returns , I want the link to execute the onclick functions that were attached to it.
Is there a way to do what I want ? I'm using jQuery if it makes a difference.
Here's an attempt at an example :
$("#link").click(function1);
$("#link").click(function2);
$("#link").click(function(){
firstFunctionToBeCalled(function (){
// ok, now execute function1 and function2
});
}); // somehow this needs to be the first one that is called
function firstFunctionToBeCalled(callback){
// here some user input is expected so function1 and function2 must not get called
callback();
}
All this is because I'm asked to put some confirmation boxes (using boxy) for a lot of buttons and I really don't want to be going through every button.
If I understand you correctly, is this wat you wanted to do..
var originalEvent = page.onclick; //your actual onclick method
page.onclick = handleinLocal; //overrides this with your locaMethod
function handleinLocal()
{ ...your code...
originalEvent ();
// invoke original handler
}
I would use jQuery's unbind to remove any existing events, then bind a function that will orchestrate the events I want in the order I want them.
Both bind and unbind are in the jQuery docs on jquery.com and work like this...
$(".myClass").unbind("click"); // removes all clicks - you can also pass a specific function to unbind
$(".myClass").click(function() {
myFunctionA();
myFunctionB($(this).html()); // example of obtaining something related to the referrer
});
An ugly hack will be to use the mousedown or mouseup events. These will be called before the click event.
If you can add your event handler before the rest of handlers, you could try to use jQuery's stopImmediatePropagation

Categories