Is it reasonably fine to bind an event handler to an element both on the 'input' and 'propertychange' events to target support for IE8 and other browsers?
$('.element').on('input propertychange', function(){...});
Or are there pitfalls to doing this?
Edit
Is there a jQuery plugin I can use to support old version of IE?
It's not exactly the same. It'll fire when there are JavaScript changes, and not just user changes.
This means that a major pitfall is that you can have infinite recursion if the handler provided makes a JavaScript change to the same input, or if there's any sort of circular reference, where inputA changes inputB, which changes inputA.
I was actually working on this earlier today, hoping to find any small differences in the event object that would let me differentiate between user originating changes, and JavaScript changes, but I could find none.
Edit
See this blog post for a possible jQuery plugin.
Related
If it's possible to somehow monitor a change in a div's DOM then that would be my solution - that will be enough to fire my event handler, but in case that's not possible - this is my problem:
I have a div, some javascript function (out of my control) will add or remove an image to this div (potentially nested in several divs/spans).
I need to attach an event (if possible using jQuery) that will fire when this particular image is added or not.
EDIT: To clarify - when I say added - I don't mean some sort of toggle of it's display attribute, I mean literally completely added or completely removed.
You can use the mutation events for that purpose. Be aware that some of those events are deprecated by now.
$('div').on( 'DOMSubtreeModified', function( event ) {
// something was changed
});
If you just need to know if some node was added, use
$('div').on( 'DOMNodeInserted', function( event ) {
// something was changed
});
The event object will give you further information about what exactly happend.
Since you asked for an alternative, there is the jQuery livequery plugin. AFAIK, i'll also use the Mutation Events if available, but it claims to be compatible with all browsers jQuery supports. That means, they will use a fallback solution (most likely intervall timers) to check for changes in incompatible browsers.
Further read: Mutation Events
I need to reliably detect the state change of radio buttons/checkboxes on my page in order to watch if the form was modified or not. Now, this is a completely separate script, I cannot modify anything that controls the form.
Right now, I can see only two ways of doing this:
onchange event handler, which helps with textboxes, textareas and selects, but is not fired for checkboxes/radiobuttons
onclick event handler, which is not reliable, because users often use hotkeys to change the values of these elements.
What am I missing here? Is there a way to reliably detect that checkbox was checked/unchecked?
UPDATE: As you guys pointed out, change event is really fired on checkboxes/radiobuttons, despite the fact that w3schools says it is only for text inputs
However, my problem turned out to be that the values of checkboxes/radiobuttons are set via setAttribute in scripts and in that case the event is not fired.
Is there anything I can do in this case?
See: http://www.quirksmode.org/dom/events/change.html.
It says that all major browsers support change event but the IE's implementation is buggy.
IE fires the event when the checkbox or radio is blurred, and not when it is activated. This is a serious bug that requires the user to take another action and prevents a consistent cross-browser interface based on the change event on checkboxes and radios.
I think you can overcome IE's bug with this trick. blur() elements when they focued! (Use something like $('input[type=radio]').focus(function(){$(this).blur();}); in jQuery or use pure javascript)
Ok, after some digging, here is what I found out. Note, this is applicable to Firefox, and, probably to Firefox only. Since in this case I was dealing with internal application, this was enough for me.
So, basically, in order to reliably detect changes in checkbox/radiobutton state in Firefox, you need to do two things:
Set up custom Firefox's event handlers CheckboxStateChange and RadioStateChange for checkbox and radiobutton respectively. These events will be fired when the user changes the inputs or when it is modified via script, using setAttribute, however, these events are not fired, when the state is changed in the script, using checked or selected properties of these elements, this is why we need ...
Watch the changes of the checked property using Object.watch
Standard onchange event is no good, since it only fired when user changes the value directly.
Damn, this thing is broken...
If people get interested, I'll post some code.
One of the most recommended ways to listen for a change of a input text field is to bind that field to a key up event. That works fine in most cases. But there are cases where this is not working. In Firefox for example one has the option, when text is already selected, to delete it by using the context menu. And this doesn't fire a key up event. I haven't found any event that is fired for that text field when doing this.
Any suggestions how I can react on this (in pure Javascript or jQuery)?
See the oninput event, and my write up about it here.
oninput fires for all forms of text input - including cut, paste, undo, redo, clear, drag and drop and spelling corrections. It's a HTML 5 event which isn't supported in Internet Explorer 8 and lower (but it is in the latest IE 9 preview). However, Internet Explorer supports a proprietary event on all DOM objects - onpropertychange. This fires whenever the value of an input element changes.
I didn't notice you'd tagged with jquery — since you did, it's probably worth mentioning that I wrote a plugin to implement the oninput event cross browser. You can find it here.
The best way is to store the value on a focus event and recheck the value on a blur event. Listening to key events fires a lot of usually redundant processes. Most of the time, you are only interrested in a field value when the user is done inputting (or deleting) it.
This works cross browser, though delegating focus/blur can be an issue in some browsers. The easiest way is to apply blur/focus listeners to the element directly.
Only exceptions are implementations like autosuggest/complete and even then you might want to debounce key input so it only fires when the user idles for a few hundred miliseconds.
I've been wondering if browsers fire any event when select box is dynamicaly populated? I would expect 'onchange' being fired, but that doesn't happen.
As it has been pointed out already, onchange event is responsible for User-made changes. However, when you change the DOM programmatically, the DOM Mutation event is fired by some browsers, but that standard is not very well supported.
Mutation events might be what you're looking for. They feature options like DOMSubtreeModified, DOMNodeInserted, and some others. Apparently there is a jQuery project on github to include support for Mutation-events. Check it out at http://github.com/jollytoad/jquery.mutation-events/tree/master
Not that I'm aware of. For the most part, the only events that are dispatched are those initiated by the user.
A <select> receiving new options is technically initiated by the browser (even though it may happen as a result of a user action).
Although I agree that it would be particularly useful and cool if you could listen for changes on any arbitrary DOM property and bind handlers to react to those changes.
You can, however, look into a signals and slots implementation in javascript which might help you.
I have the following problem:
I have an HTML textbox (<input type="text">) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).
I want to be notified in my script every time the value of that textbox changes, so I can react to it.
I've tried this:
txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.
Is there another event I can listen to, that i'm not aware of?
I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com)
As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
myListener(year,month,day);
return orig(year,month,day,hide);
});
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well.
addEventListener("DOMControlValueChanged" will fire when a control's value changes, even if it's by a script.
addEventListener("input" is a direct-user-initiated filtered version of DOMControlValueChanged.
Unfortunately, DOMControlValueChanged is only supported by Opera currently and input event support is broken in webkit. The input event also has various bugs in Firefox and Opera.
This stuff will probably be cleared up in HTML5 pretty soon, fwiw.
Update:
As of 9/8/2012, DOMControlValueChanged support has been dropped from Opera (because it was removed from HTML5) and 'input' event support is much better in browsers (including less bugs) now.
IE has an onpropertychange event which could be used for this purpose.
For real web browsers (;)), there's a DOMAttrModified mutation event, but in a couple of minutes worth of experimentation in Firefox, I haven't been able to get it to fire on a text input when the value is changed programatically (or by regular keyboard input), yet it will fire if I change the input's name programatically. Curiouser and curiouser...
If you can't get that working reliably, you could always just poll the input's value regularly:
var value = someInput.value;
setInterval(function()
{
if (someInput.value != value)
{
alert("Changed from " + value + " to " + someInput.value);
value = someInput.value;
}
}, 250);
Depending on how the external javascript was written, you could always re-write the relevant parts of the external script in your script and have it overwrite the external definition so that the change event is triggered.
I've had to do that before with scripts that were out of my control.
You just need to find the external function, copy it in its entirety as a new function with the same name, and re-write the script to do what you want it to.
Of course if the script was written correctly using closures, you won't be able to change it too easily...
Aside from getting around the problem like how noah explained, you could also just create a timer that checks the value every few hundred milliseconds.
I had to modify the YUI datable paginator control once in the manner advised by Dan. It's brute force, but it worked in solving my problem. That is, locate the method writing to the field, copy its code and add a statement firing the change event and in your code just handle that change event. You just have to override the original function with that new version of it. Polling, while working fine seems to me a much more resource consuming solution.