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”>


type=“text/javascript”
language=“javascript”>

window.onload = focusForm;

function focusForm(){


if(document.getElementById(“username”)){

document.getElementById(“username”).focus();

}

}


</cfsavecontent>

<cfhtmlhead
text=“#javascriptToInject#”>

<cfoutput>

<form
action=https://#application.hostSecure##cgi.script_name#&#8221;
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>

2 thoughts on “Custom Tags, and cfhtmlhead

  1. 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);

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s