I have the following code:
function showAddrBox() {
var prompt = document.getElementById('addr_prompt');
prompt.style.display = 'block';
document.generic_form.address.style.display = 'block';
document.generic_form.onsubmit = validateAddrForm;
}
function hideAddrBox() {
var prompt = document.getElementById('addr_prompt');
prompt.style.display = 'none';
document.generic_form.address.style.display = 'none';
document.generic_form.onsubmit = null;
}
The problem is that sometimes I have additional functions attached to onSubmit that I want to preserve. I want to be able to add and remove individual functions from the onSubmit event, not just set them with onsubmit =. In other words, I need a way to accomplish something like this:
document.form.onsubmit += function;
document.form.onsubmit -= function;
Any ideas?
Quirksmode has a wonderful article about advanced event registration.
Short form is: You can bind multiple events using addEventListener (attachEvent in older versions of IE).
if (someform.addEventListener) {
someform.addEventListener('submit', somefunc, false);
} else {
someform.attachEvent('onsubmit', somefunc);
}
To remove them you can use removeEventListener and detachEvent respectively.
Pretty quickly you'll get annoyed by repetitively typing addEventListener and attachEvent, and you might consider making some generic code to bind events for you. Fortunately, other programmers have had the same idea, and many libraries are available that handle event management elegantly. jQuery tends to be the library of choice, because binding an event is as simple as:
$('#formid').submit(somefunc);
the generic event binding method is:
$('#formid').on('submit', somefunc);
to unbind you can use:
$('#formid').off('submit', somefunc);
Although all of this is well documented in the jQuery API.
Use element.addEventListener("eventName", callbackFunction, false) and element.removeEventListener("eventName", callbackFunction).
Where eventName is the name of the handler without the 'on'. So onsubmit becomes submit.
For documentation of the two functions, see:
https://developer.mozilla.org/en/DOM/element.addEventListener
https://developer.mozilla.org/en/DOM/element.removeEventListener
What I would do is have one onSubmit function right on the form that orchestrates the rest of the functions, performs logic on what to do when. At the end of that function execution you can return true if you want to proceed with the submission or return false if you don't.
u can mention two or more functions for a form like below.
<form name="formaname" onsubmit="function1(),function2()">
more on onsubmit
Related
Adding an event handler is pretty easy.
Now I'd like to inhibit default behavior, e.g. highlighting a text when keeping it touched for a while.
I found the preventDefault method. However I don't see how to provide the required event object to myFunction
<!DOCTYPE html>
<html>
<body>
<h1>Event Handling</h1>
<p ontouchstart="myFunction(true)" ontouchend="myFunction(false)">Touch this! </p>
<p id="demo">demo</p>
<script>
function myFunction(state) {
document.getElementById("demo").innerHTML = (state? "Hello World": " ");
event.preventDefault(); // how to get access to the event object ?
}
</script>
</body>
</html>
Or am I on the wrong search path?
Adding an event handler is pretty easy.
It is. But, you're doing it the 25+ year old legacy way, which should not be used today.
The event object is not automatically passed to callbacks when you use the legacy inline event attributes, such as onXyz.
Instead, use the modern approach to event handling and use .addEventListener() separately in your JavaScript. Then, the event object reference will automatically be passed as the first argument to your callback.
Now, because you want to pass your own argument to your callback, you'll need to wrap your actual callback in an anonymous function that will be the the "official" event handler and that one will receive the event argument. Then, in that wrapper, you can call your desired function and pass along the event as well as your custom argument(s).
Since not all devices support touch events, you need to check to see if they are supported by the device before you use them. Below, I've done a basic feature detection check, but read this for more comprehensive approaches.
In addition, you may also want to prevent the event from bubbling up to ancestor elements that may have event handlers registered to them as well. If so, you should also add event.stopPropagation().
Also, you should avoid .innerHTML when you can (almost always) as it has performance and security implications. Since you aren't actually getting or setting any HTML, use .textContent.
<!DOCTYPE html>
<html>
<body>
<h1>Event Handling</h1>
<p class="touch">Touch this! </p>
<p id="demo">demo</p>
<script>
// Get your DOM references just once instead of each time your functions run
const touchP = document.querySelector(".touch");
const demo = document.getElementById("demo");
// Not all devices support touch events, you should check first.
if(touchP.touchstart){
// The registered callback function will automatically be passed an event reference
touchP.addEventListener("touchstart", function(event){
// You can now call your desired function and pass the event and your argument
myFunction(event, true);
});
touchP.addEventListener("touchend", function(event){
myFunction(event, false)
});
} else {
demo.textContent = "Touch not supported on this device.";
}
function myFunction(event, state) {
event.preventDefault();
event.stopPropagation(); // If you don't want the event to bubble
// You probably didn't want a space character returned if state == false.
// Instead, return an empty string: ""
demo.textContent = state ? "Hello World" : "";
}
</script>
</body>
</html>
You have to pass the event to your function when you call it.
<p ontouchstart="myFunction(event, true)" ontouchend="myFunction(event, false)">Touch this! </p>
function myFunction(event, state) {
document.getElementById("demo").innerHTML = (state? "Hello World": " ");
event.preventDefault(); // how to get access to the event object ?
}
The event exist in the event declarations.
Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller.
I bind some onclick events to a button, but I find that they sometimes execute in an order I did not expect.
Is there a way to ensure order, or how have you handled this problem in the past?
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
$('#mydiv').click(function(e) {
// maniplate #mydiv ...
$('#mydiv').trigger('mydiv-manipulated');
});
$('#mydiv').bind('mydiv-manipulated', function(e) {
// do more stuff now that #mydiv has been manipulated
return;
});
Something like that at least.
Dowski's method is good if all of your callbacks are always going to be present and you are happy with them being dependant on each other.
If you want the callbacks to be independent of each other, though, you could be to take advantage of bubbling and attach subsequent events as delegates to parent elements. The handlers on a parent elements will be triggered after the handlers on the element, continuing right up to the document. This is quite good as you can use event.stopPropagation(), event.preventDefault(), etc to skip handlers and cancel or un-cancel the action.
$( '#mybutton' ).click( function(e) {
// Do stuff first
} );
$( '#mybutton' ).click( function(e) {
// Do other stuff first
} );
$( document ).delegate( '#mybutton', 'click', function(e) {
// Do stuff last
} );
Or, if you don't like this, you could use Nick Leaches bindLast plugin to force an event to be bound last: https://github.com/nickyleach/jQuery.bindLast.
Or, if you are using jQuery 1.5, you could also potentially do something clever with the new Deferred object.
I had been trying for ages to generalize this kind of process, but in my case I was only concerned with the order of first event listener in the chain.
If it's of any use, here is my jQuery plugin that binds an event listener that is always triggered before any others:
** UPDATED inline with jQuery changes (thanks Toskan) **
(function($) {
$.fn.bindFirst = function(/*String*/ eventType, /*[Object])*/ eventData, /*Function*/ handler) {
var indexOfDot = eventType.indexOf(".");
var eventNameSpace = indexOfDot > 0 ? eventType.substring(indexOfDot) : "";
eventType = indexOfDot > 0 ? eventType.substring(0, indexOfDot) : eventType;
handler = handler == undefined ? eventData : handler;
eventData = typeof eventData == "function" ? {} : eventData;
return this.each(function() {
var $this = $(this);
var currentAttrListener = this["on" + eventType];
if (currentAttrListener) {
$this.bind(eventType, function(e) {
return currentAttrListener(e.originalEvent);
});
this["on" + eventType] = null;
}
$this.bind(eventType + eventNameSpace, eventData, handler);
var allEvents = $this.data("events") || $._data($this[0], "events");
var typeEvents = allEvents[eventType];
var newEvent = typeEvents.pop();
typeEvents.unshift(newEvent);
});
};
})(jQuery);
Things to note:
This hasn't been fully tested.
It relies on the internals of the jQuery framework not changing (only tested with 1.5.2).
It will not necessarily get triggered before event listeners that are bound in any way other than as an attribute of the source element or using jQuery bind() and other associated functions.
The order the bound callbacks are called in is managed by each jQuery object's event data. There aren't any functions (that I know of) that allow you to view and manipulate that data directly, you can only use bind() and unbind() (or any of the equivalent helper functions).
Dowski's method is best, you should modify the various bound callbacks to bind to an ordered sequence of custom events, with the "first" callback bound to the "real" event. That way, no matter in what order they are bound, the sequence will execute in the right way.
The only alternative I can see is something you really, really don't want to contemplate: if you know the binding syntax of the functions may have been bound before you, attempt to un-bind all of those functions and then re-bind them in the proper order yourself. That's just asking for trouble, because now you have duplicated code.
It would be cool if jQuery allowed you to simply change the order of the bound events in an object's event data, but without writing some code to hook into the jQuery core that doesn't seem possible. And there are probably implications of allowing this that I haven't thought of, so maybe it's an intentional omission.
Please note that in the jQuery universe this must be implemented differently as of version 1.8. The following release note is from the jQuery blog:
.data(“events”): jQuery stores its event-related data in a data object
named (wait for it) events on each element. This is an internal data
structure so in 1.8 this will be removed from the user data name space
so it won’t conflict with items of the same name. jQuery’s event data
can still be accessed via jQuery._data(element, "events")
We do have complete control of the order in which the handlers will execute in the jQuery universe. Ricoo points this out above. Doesn't look like his answer earned him a lot of love, but this technique is very handy. Consider, for example, any time you need to execute your own handler prior to some handler in a library widget, or you need to have the power to cancel the call to the widget's handler conditionally:
$("button").click(function(e){
if(bSomeConditional)
e.stopImmediatePropagation();//Don't execute the widget's handler
}).each(function () {
var aClickListeners = $._data(this, "events").click;
aClickListeners.reverse();
});
function bindFirst(owner, event, handler) {
owner.unbind(event, handler);
owner.bind(event, handler);
var events = owner.data('events')[event];
events.unshift(events.pop());
owner.data('events')[event] = events;
}
just bind handler normally and then run:
element.data('events').action.reverse();
so for example:
$('#mydiv').data('events').click.reverse();
You can try something like this:
/**
* Guarantee that a event handler allways be the last to execute
* #param owner The jquery object with any others events handlers $(selector)
* #param event The event descriptor like 'click'
* #param handler The event handler to be executed allways at the end.
**/
function bindAtTheEnd(owner,event,handler){
var aux=function(){owner.unbind(event,handler);owner.bind(event,handler);};
bindAtTheStart(owner,event,aux,true);
}
/**
* Bind a event handler at the start of all others events handlers.
* #param owner Jquery object with any others events handlers $(selector);
* #param event The event descriptor for example 'click';
* #param handler The event handler to bind at the start.
* #param one If the function only be executed once.
**/
function bindAtTheStart(owner,event,handler,one){
var eventos,index;
var handlers=new Array();
owner.unbind(event,handler);
eventos=owner.data("events")[event];
for(index=0;index<eventos.length;index+=1){
handlers[index]=eventos[index];
}
owner.unbind(event);
if(one){
owner.one(event,handler);
}
else{
owner.bind(event,handler);
}
for(index=0;index<handlers.length;index+=1){
owner.bind(event,ownerhandlers[index]);
}
}
I have same issue and found this topic. the above answers can solve those problem, but I don't think them are good plans.
let us think about the real world.
if we use those answers, we have to change our code. you have to change your code style. something like this:
original:
$('form').submit(handle);
hack:
bindAtTheStart($('form'),'submit',handle);
as time goes on, think about your project. the code is ugly and hard to read! anthoer reason is simple is always better. if you have 10 bindAtTheStart, it may no bugs. if you have 100 bindAtTheStart, are you really sure you can keep them in right order?
so if you have to bind same events multiple.I think the best way is control js-file or js-code load order. jquery can handle event data as queue. the order is first-in, first-out. you don't need change any code. just change load order.
Here's my shot at this, covering different versions of jQuery:
// Binds a jQuery event to elements at the start of the event chain for that type.
jQuery.extend({
_bindEventHandlerAtStart: function ($elements, eventType, handler) {
var _data;
$elements.bind(eventType, handler);
// This bound the event, naturally, at the end of the event chain. We
// need it at the start.
if (typeof jQuery._data === 'function') {
// Since jQuery 1.8.1, it seems, that the events object isn't
// available through the public API `.data` method.
// Using `$._data, where it exists, seems to work.
_data = true;
}
$elements.each(function (index, element) {
var events;
if (_data) {
events = jQuery._data(element, 'events')[eventType];
} else {
events = jQuery(element).data('events')[eventType];
}
events.unshift(events.pop());
if (_data) {
jQuery._data(element, 'events')[eventType] = events;
} else {
jQuery(element).data('events')[eventType] = events;
}
});
}
});
In some special cases, when you cannot change how the click events are bound (event bindings are made from others' codes), and you can change the HTML element, here is a possible solution (warning: this is not the recommended way to bind events, other developers may murder you for this):
<span onclick="yourEventHandler(event)">Button</span>
With this way of binding, your event hander will be added first, so it will be executed first.
JQuery 1.5 introduces promises, and here's the simplest implementation I've seen to control order of execution. Full documentation at http://api.jquery.com/jquery.when/
$.when( $('#myDiv').css('background-color', 'red') )
.then( alert('hi!') )
.then( myClickFunction( $('#myID') ) )
.then( myThingToRunAfterClick() );
JQuery has great support for custom events - .bind("foo", function(e).... However what if the mechanic of triggering the event is not ready yet and has to be constructed only on those elements that have the event bound on?
For example I want a scrollin event that gets fired when an element is scrolled into a viewport. To do this, I would onscroll have to check all the elements and trigger scrollin on those that were outside the viewport and now are inside. This is not acceptable.
There are some tricks to speed it up. For example one of the plugins for this checks all the elements in "private" $.cache and does the checking only on those that have scrollin event bound.
But that's also ugly. What I need is an additional callback for the binding of the event (additional to the callback for handling) that would take care of the scroll management, that is to put the element(s) into some elementsCheckOnScrol cache array.
I'm looking for something like:
$.delegateBind("scrollin", function(jqSelection) { ... });
element.bind("scrollin", function(e) {..}); //Calls ^ after internal bind management
Edit: This would be nice api!
$.bind("bind", function(onWhat) { ... })
:-)
If I'm not misunderstanding you, you could patch the bind method like this:
(function($) {
var oldBind = $.fn.bind;
$.fn.bind = function(name) {
if(name === "scrollin") {
delegateFunction(this);
}
oldBind.apply(this, arguments);
};
})(jQuery);
What it does is checking whether a scrollin is being bound, and if so, calls your delegate function. After that it simply calls the original bind function which does all jQuery things like it does regularly.
After having added this code, you could use it like this: http://jsfiddle.net/pimvdb/g4k2G/.
function delegateFunction(selection) {
alert(selection.length);
}
$('a').bind('scrollin', function() {});
Note that this does not support object literals being passed to .bind (only (name, func)), but you could implement that as well.
I found an $.event.special API, but I don't know "how much" public it is. It is not in the docs and has been changed at least once before. http://benalman.com/news/2010/03/jquery-special-events/
I have a Dojo SubmitButton with jsId="saveParamButtonWidget". I overrided its onClick method by putting:
saveParamButtonWidget.onClick = editParam
I defined the editParam() function like this:
function editParam(eventObj) {
dojo.stopEvent(eventObj);
// ...
}
dojo.stopEvent() is supposed to stop event bubbling and default processing. However, the browser will submit the form anyway. I also tried with the following:
function editParam(eventObj) {
eventObj.stopPropagation();
eventObj.preventDefault();
// ...
}
Same thing. The only way I've managed to prevent form submission is by returning "false" from the event handler:
function editParam(eventObj) {
// ...
return false;
}
Can someone tell me why the first two ways did not work? Thanks.
Okay, after doing some digging through the source, I believe I can answer your question definitively.
The reason dojo.stopEvent() doesn't work, but return false does, is entirely due to how dijit.form.Button is coded. If you're interested, it's time for a little field trip. Keep your hard hats on.
When a dijit.form.Button is clicked...
The button's _onButtonClick method is invoked. (This is hooked up in the template, to the special ondijitclick event which captures not only mouse click but also certain keypresses, for a11y purposes.)
The _onButtonClick method first invokes the _onClick method, which, presuming the button is not disabled (which it's not in this case), invokes and returns the result of the onClick method. This is of particular interest since it's the method you're overriding!
Coming back to _onButtonClick, if _onClick returned precisely false (e.g. if your onClick handler returned false), _onButtonClick immediately bails out. This is why returning false makes your code work as desired. But what happens if it doesn't bail out there? Let's follow the trail further...
Next, _onButtonClick checks whether this button not a descendant of an actual HTML form, but is a descendant of a widget with an _onSubmit method (duck-typing). I'm assuming that in your case it is inside a real form (dijit.form.Form counts), so we'll skip over this. (I am under the impression that this code path wouldn't actually end up submitting, whereas yours apparently does.)
One final condition is checked: if the button has a valueNode defined (it does), the click method of this node is invoked. Unfortunately, this produces an entirely new event object on an invisible input type="submit" node under your form, and thus anything you tried to tell the original event is rendered immaterial, and the form goes on to submit! This is why dojo.stopEvent did not work - this code in dijit.form.Button pays it absolutely no heed.
I cooked this up as a somewhat-limited proof of concept (be sure to open firebug/etc. to get the logs): http://jsfiddle.net/Bf5H8/
Perhaps this is something that should be logged as a bug, but I suppose the initial thought may have been that supporting the well-known return false mechanism would be enough.
All this being said, it's quite possible that overriding onSubmit of the form is more in-line with your interests than overriding the button's onClick anyway (as S.Jones suggested), but at least this should solve the mystery.
Interesting question. +1
I believe you have to use dojo.connect to connect your function to a DOM event to get access to those methods with an event object.
See: The Event Object (DojoTollkit.org Reference Guide)
The Event Object
When you connect a function to a DOM
event with dojo.connect,
Dojo passes your function a normalized
event object. This means that,
regardless of the client's browser,
you can count on a set of standard
attributes about the event and a set
of methods to manipulate the event.
Assume that your function has been
called by dojo.connect and takes an
argument named event, like:
dojo.connect(dojo.byId("node"), "onclick", function(event){
// the var 'event' is available, and is the normalized object
});
...
Dojo normalizes the following methods with an event object:
event.preventDefault — prevent an event's default behavior (e.g., a link from loading a new page)
event.stopPropagation — prevent an event from triggering a parent node's event
Additionally, dojo.stopEvent(event)
will prevent both default behavior any
any propagation (bubbling) of an
event.
That said, placing a function like the one below in your form to perform some logic before submitting it, is a fairly clean, easily understood & maintainable approach.
<script type="dojo/method" event="onSubmit">
if (!this.validate()) { // or whatever else you'd like to evaluate
// insert calls here...
return false;
}
return true;
<script>
Cheers.
I had the same issue for using dojo.stopEvent
This issue is solved the form submission issue like this - here it is a simple form used to connect through dojo:
this.formId = dojo.byId("formId");
dojo.connect(this.formId, 'onsubmit', function(evt) {
var val_main = validate_this_form(0);
if(val_main == false)
dojo.stopEvent(evt);
});
I can't fire personal events using Javascript in IE. In Firefox work great.
My code is:
var evento;
if(document.createEventObject)
{
evento = document.createEventObject();
document.fireEvent('eventoPersonal', evento);
}
//FF
else
{
evento = document.createEvent('Events');
evento.initEvent('eventoPersonal',true,false);
document.dispatchEvent(evento);
}
But when try to execute document.fireEvent('eventoPersonal', evento); in IE, it doesn't work. How can I fire NO custom events in IE?
In Internet Explorer I get the error: "Invalid arguments" in the line where execute document.fireEvent('eventoPersonal', evento);
Dean Edward's describes how to fire cutsom events in IE
http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/
Its near the bottom of the article
var currentHandler;
if (document.addEventListener) {
// We've seen this code already
} else if (document.attachEvent) { // MSIE
document.documentElement.fakeEvents = 0; // an expando property
document.documentElement.attachEvent("onpropertychange", function(event) {
if (event.propertyName == "fakeEvents") {
// execute the callback
currentHandler();
}
});
dispatchFakeEvent = function(handler) {
// fire the propertychange event
document.documentElement.fakeEvents++;
};
}
I think the answer is - in IE you can not fire events that are not on this list:
MSDN - DHTML Events
From what I can gather, frameworks store a registry of the "custom" event names and you must use their implementation specific trigger and handle functions for custom events. For example, prototype uses the ondatavailable event to pass through their custom events behind the scenes.
You may want to consider using a library to abstract this. Both prototype an jquery will handle this for you. Jquery is especially good at allowing you to create an event with very simple code.
Jquery's documentation is available here:
http://docs.jquery.com/Events
In IE11 document.dispatchEvent still doesn't work, but now attachEvent is missing too, so the other solution is not going to work either. However, I came up with one even uglier. :) It involves replacing the addEventListener method and goes on like this:
var oldEventListener = document.addEventListener;
document.addEventListener = function (event, func, capture) {
if (event == "MyPreciousCustomEvent") {
document.MyPreciousCustomEvent = func;
}
oldEventListener.call(document, event, func, capture);
};
...
$(function () {
try {
document.MyPreciousCustomEvent("MyPreciousCustomEvent", {});
} catch (e) {}
});
Hope this helps someone.
As I read the relevant MSDN article page on the createEventObject method, it appears as though it isn't used for creating custom event - it is used for creating custom objects that can be passed to already existing events.
Description:
Generates an event object to pass event context information when you use the fireEvent method.
http://msdn.microsoft.com/en-us/library/ms536390%28VS.85%29.aspx
Update: You are getting the "invalid arguments" error because 'eventoPersonal' is not an acceptable event to fire.
Yeah referring to #Don Albrecht, you can use jquery trigger() method more on http://api.jquery.com/trigger/