Assigning Event Handlers in JS-Written UI, Painlessly
-
If your WebDialog's UI is a function of the model's content, you will need to use JavaScript to create the UI. This is easy if you follow this model.
<!-- a.html --> <html> <body onload=init()> <script> var giggle = function() { alert('That tickles!') } function init() { var btn = document.createElement( 'button' ); btn.innerHTML = 'Click Me!'; document.body.appendChild( btn ); btn.onclick = giggle; } </script> </body> </html>
You can't document.write() your UI and you can't assign event handlers before you attach the listeners to the DOM. Your script, or your link to a .js file, should be the last thing before </body> (never in the <head> section).
-
I always keep the links to JS in the HEAD. I attach an init function to the DOMContentLoaded event (it's triggered immediately after the HTML is loaded - but doesn't wait for all images and other resources like onLoad does.) and that works fine. Standard web-design practice.
-
@thomthom said:
I always keep the links to JS in the HEAD.
That risks being bitten by The Bug from Hell, which you definitely don't want. Also, see http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309 . Formerly Yahoo's front-end guru, Souder is now with Google.
-
"The Bug from Hell"?
-
@thomthom said:
"The Bug from Hell"?
http://21st-century-languages.blogspot.com/2009/08/bug-from-hell.html
-
In my example code, I attach an anonymous function to a variable;
var foo = function() {...}
Later, this function is attached to the "onclick" method:
btn.onclick = foo
Suppose you have several buttons. You might want to pass a button number as an argument. How?
Use the button's id. Example:
var foo = function() { var which_one = this.id; ... }
Suppose you really, truly want a number:
button.id = number + '_btn';
var foo = function() { var which_one = parseInt( this.id ); ... }
-
Will the browsers accept that ID you give the element? The specs says that and ID attribute must begin with a letter. (Not sure how the browsers deal with this when they encounter it. Ignore it - or accept it?)
I'm pondering about the cache problems you have. By the sound of it we used the same method - in locating the script in the HTML. But experience different results. I'll see if I can get a developer demo of my script uploaded for comparison.
-
What version of IE do you deal with? I think most my machine now have IE8 - not sure if I ran that plugin under IE7...
-
Advertisement