I'm looking for a good example where a framework/lib like jQuery removes the need for browser-specific code. Please note that I'm not looking for an example where jQuery makes things just easier or nice but specifically something where the same code wouldn't work for all common browsers.
As it'll be used for university stuff and just meant to be an example a very simple thing would be great (otherwise I'd probably use e.which vs e.keyCode)
Event handling is a good example, as it is so important for today's web applications.
element.addEventListener does not work in IE8 and below. These things are different in IE:
You have to use element.attachEvent and 'on<event>':
element.addEventListener('click', handler, false); // W3C
// vs.
element.attachEvent('onclick', handler); // IE
As IE's event model is a bit different, it does not support listing to events in the capture phase:
element.addEventListener('click', handler, true); // W3C
// vs
// not possible :( // IE
IE does not pass the event to the handler (it is available in via window.event):
function handler(event) {
event; // W3C
// vs
window.event; // IE
}
Inside the event handler, this does not refer to element the handler is bound to, but to window:
function handler() {
alert(window === this); // true // IE
}
Notice: This is only the case for event handlers bound via attachEvent. In inline event handlers and the ones assigned to the onclick property, this refers to the element.
Different properties of the event object (e.g. no event.stopPropagation):
event.stopPropgation(); // W3C
// vs.
event.cancelBubble = true; // IE
Except for the capturing, all these things can be dealt with by creating an appropriate wrapper function (what jQuery is basically doing). How such a method could look like can be found in my answer to this question.
You can find more information about these differences on quirksmode.org:
this keywordYou can talk about jQuery's normalised event object, and in particular how it simplifies getting the event's target/sourceElement, eliminating the need for code like this:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
(From http://www.quirksmode.org/js/events_properties.html#target)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With