As an answer to the question of 'How do you automatically set the focus to a textbox when a web page loads?', Espo suggests using
<body onLoad="document.getElementById('<id>').focus();">
Ben Scheirman replies (without further explanation):
Any Javascript book will tell you not to put handlers on the body element like that
Why would this be considered bad practice? In Espos answer, an 'override' problem is illustrated. Is this the only reason, or are there any other problems? Compatibility issues?
JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked. External JavaScript: JavaScript can also be used as external files. JavaScript files have file extension .
JavaScript Event Handlers Event handlers can be used to handle and verify user input, user actions, and browser actions: Things that should be done every time a page loads. Things that should be done when the page is closed. Action that should be performed when a user clicks a button.
The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers. Syntax: element.
Using onLoad
is becoming less and less common because callbacks can't be stacked using this method, i.e. new onload
definitions override the old ones.
In modern frameworks like jQuery and its .load()
, callbacks can be stacked and there are no conflicts when using different scripts, plugins, etc. on the same page.
Also, it is widely regarded good practice to keep the markup separate from the code, so even if one would want to use onload
(which is perfectly okay if you control the complete environment and know what you're doing) one would attach that event on the scripting side either in the head
or a separate javaScript file:
window.onload = function() { document.getElementById...... }
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