Categories:

JavaScript cut-and-pasters, listen up!

If you're a JavaScript user (as opposed to simply a developer), knowing how to embed more than one function into an event handler is especially important. Often times, two scripts you're trying to paste onto the same page both attempt to attach itself to the BODY onload event handler. For example, you may have two scripts that look like the following:

<body onload="dothat()">

<!------------SCRIPT 1-------------->
<script>
function dothis(){
"
"
"
}
window.onload=dothis
</script>
<!------------END OF SCRIPT 1--->

<!-------------SCRIPT 2---------------->
<script>
function dothat(){
"
"
"
}
</script>
<!------------END OF SCRIPT 2------>

</body>

Function dothis() (which belongs to script 1) tries to attach itself to the BODY onload event handler through the JavaScript syntax "window.onload=dothis", while function dothat() (which belongs to script 2) does so in a more traditional way, through the HTML syntax "onload=dothat()" Which function will actually get executed when the page loads? Well, function dothis(), and ONLY function dothis(). This is so because JavaScript always chooses the last "body onload=...." statement to execute, whether it's defined using the regular HTML syntax, or JavaScript syntax. Good for JavaScript, but in this case, it's NOT what you want! In order for both of the scripts to work on the page, you have to come up with a way to allow both functions to execute when the page loads. The solution? You guessed it! Simply embed both of the functions inside the body tag, separating each with a semicolon, remembering to remove the now useless "window.onload=dothis" line from script 1. So, the result would look like:

<body onload="dothat();dothis()">

<!------------SCRIPT 1-------------->
<script>
function dothis(){
"
"
"
}
</script>
<!------------END OF SCRIPT 1--->

<!-------------SCRIPT 2---------------->
<script>
function dothat(){
"
"
"
}
</script>
<!------------END OF SCRIPT 2------>

</body>

Now the two scripts will both function properly on your page. Keep this technique at heart, because, living the life of a JavaScript cut-and-paster, it will definitely come in handy every once in a while!