Aarrgghh!!

Custom Tags, and cfhtmlhead

I've been doing a fair amount of work with custom tags and JavaScript DOM manipulation. One of the things with which I've struggled with is organizing my code. Do I put the JavaScript in the custom tag? Do I put it in central .js files? What if the script I've written will only be called from one custom tag and one custom tag only?

Well I haven't worked out all of the answers, but I do have a solution for single use scripts: Use <cfhtmhead> to inject the script into the html header from the custom tag. It keeps all of the connected code together, but still does proper, degradable, properly-separated JavaScript and HTML.

Here's an example of this in use:

<cfsavecontent variable="javascriptToInject">

<script type="text/javascript" language="javascript">

window.onload = focusForm;

function focusForm(){

if(document.getElementById("username")){

document.getElementById("username").focus();

}

}

</script>

</cfsavecontent>

<cfhtmlhead text="#javascriptToInject#">

<cfoutput>

<form action="https://#application.hostSecure##cgi.script_name#" method="post">

<label for="username">Username</label></dt>

<input type="text" id="username" name="username" />

<label for="password">Password</label></dt>

<input type="password" id="password" name="password" />

<input type="submit" name="signin" value="Sign In"/>

</form>
</cfoutput>


August 14, 2007 Posted by Terrence Ryan at 10:24 PM

ColdFusion, Web Development,



Comments

I've found cfhtmlhead to be invaluable for this purpose. I glad to see this post about it because I'm always surprised how many CF developers I run into who don't know about this tag.

On thing to keep in mind when injecting JavaScript into the page is that it is very possible the page already has an onload function defined. One way to make sure the old onload event as well as your new event get fired is to use an anonymous function like so:

window.onload = (function (old) { return function () { if (typeof old == 'function') old(); if(document.getElementById("username")); document.getElementById("username").focus(); }; })(window.onload);


Posted by: Nathan Mische at August 15, 2007 8:43 AM

Aarrgghh Guy! That's an awesome tip, Nathan.




Posted by: Terrence Ryan at August 15, 2007 9:10 AM

Posted by Who at February 9, 2012 5:13 PM

Post a comment











Remember personal info?