views:

922

answers:

4

As I begin to develop more and more compliacted Javascript solutions, I wonder what sort of options javascript gives me to monitor changes in my environment. I've seen so many solutions that constantly ping whatever element they are wanting to monitor, but for any sort of resource heavy application (or for any case depending on the standards of the developer) that becomes bloated and too hackish to be a viable method. Which brings me to my question, "What are the limitations of javascript's onchange event?". Specifically, right now I'm trying to monitor the size of the window. Is there a way to utilize the .onchange event for things like this? How would you solve this?

Thanks! I'm very interested to hear what everyone has to say.

+4  A: 

The onchange attribute is a DOM property. It is not provided by Javascript. W3schools reports that only some elements support its use, per their page about the onchange event:

Supported by the following HTML tags:

<input type="text">, <select>,
<textarea>

Supported by the following JavaScript objects:

fileUpload, select, text, textarea

If you want to monitor the size of the window you basically have two options: - use the onresize attribute - set an interval that checks via polling.

Rahul
Could whoever downvoted this please explain what the problem is with the answer?
Rahul
It wasn't me, but the problem is that you can watch for changes in the size of the window with onresize. Ie. you don't have to poll.
Andrew Hedges
OK, thanks. I added it to my answer.
Rahul
+4  A: 

The size of the window can be monitored with onresize.

The onchange event, as Rahul says, applies to fileupload, select, text and textarea. However, it only fires once focus is shifted away from the item and onto something else, and the content has changed.

Marius
A: 

Try out jQuery, it's tiny and insanely powerful.

jQuery has two function that should be of use to you: width() and height()

Example (based on example from the docs linked above):

function showWidth(ele, w) {
    $("someDiv").text("The width for the " + ele + 
                " is " + w + "px.");
}

$('#someElement').change(function () { 
  showWidth("document", $(document).width()); 
});

Of course, the same applies to height(). Good luck.

karim79
A: 
window.onresize=function(){
    exampleFunction();
}

is what I do. I am not very keen of onchange, if you changed the element with JS, you can also call the event in the same JS. (why do it like: JS -> element -> JS, when you can go: JS -> element and JS)

mike nvck