1202 Program Alarm 1202 Program Alarm - 7 months ago 26
Javascript Question

What is this "document.all" line doing?

I'm a Flex/Actionscript refugee and trying to make my way with JS/HTML5/CSS3. Some things make immediate sense but then there are others which just don't.

I am looking at this JSfiddle "Pure Javascript Draggable" and I am not understanding this line (or rather, I understand what it is doing but not how it is doing it)

x_pos = document.all ? window.event.clientX : e.pageX;


I looked up "document.all" and it seems to be shorthand for
Element.querySelectorAll()
without arguments?


Returns a non-live NodeList of all elements descended from the element
on which it is invoked that match the specified group of CSS
selectors.



  • Is that correct? So the "all" param means it is returning everything in the DOM?

  • What does a "non-live" NodeList mean? "non-live"?

  • And the actual line is... testing if window.event.clientX or e.pageX is non-null?



Basic stuff but confusing.




var selected = null, // Object of the element to be moved
x_pos = 0, y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0, y_elem = 0; // Stores top, left values (edge) of the element

// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}

// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}

// Destroy the object when we are done
function _destroy() {
selected = null;
}

// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

Answer

Is that correct? So the "all" param means it is returning everything in the DOM?

Yes. Every single one of the elements in the page is put inside a 1-D, array-like structure and handed to you.

What does a "non-live" NodeList mean? "non-live"?

NodeLists can be live or non-live. A live NodeList means the array elements change when the relevant DOM changes (i.e.: If I removed an <a> from the DOM, a live NodeList gathering all <a>s would magically lose one element). A non-live is well... one that doesn't change. (i.e.: If I removed an <a> from the DOM, a non-live NodeList gathering all <a>s would still have reference to the removed <a>).

And the actual line is... testing if window.event.clientX or e.pageX is non-null?

document.all is probably being used to check what browser is being used. In this case, it checks which event object to use, whether the global event or the local event.