10/24/2008

Adding Javascript to the BODY tag in DNN

When working with .ascx skin files, you will sometimes need to add some Javascript to the BODY tag, such as something that runs when the OnLoad event triggers.

Well, you can always add a BODY tag inside your .ascx file along with the Javascript you like and hope that the browser will understand that. Essentially, you'll end up having two BODY tags in your source code-one that is generated by DNN and one that is typed by you. Some browsers (like Chrome) understand what's happening and try to transfer the Javascript to the actual BODY tag when rendering the page, but others don't.

What you can do, though, is create a Page_Init event handler inside your .ascx file and put this code there:

Dim body As System.Web.UI.HtmlControls.HtmlGenericControl = CType(Page.FindControl("body"), System.Web.UI.HtmlControls.HtmlGenericControl) 
body.Attributes("onload") = "blablablaJavascript"


Where blablablaJavascript is your Javascript. Of course, you can do that for other events (even for other tags) as well.

If you're using a single .ascx file with no code-behind (like most do), you'll want to define a Page_Init event there. You can do that like this:

<script runat="server">

 
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init 

'Add your code here

   
End Sub 

</script>

5 comments:

Anonymous,  October 26, 2008 at 8:33 PM  

Why not just use jQuery (included in DNN5 now, easy to include in any version)

$(document).ready(function(){

//js here

});

This accomplishes the desired onload effect without the overhead of inline attributes, allowing you to include your javascript at the end of your document (like you're supposed to), optimizing your code.

Gyromyristis October 26, 2008 at 10:12 PM  

Interesting! Honestly, I never thought of that, but it sounds very nice.

Anonymous,  December 8, 2008 at 9:06 PM  

jQuery is nice and clean - a great addition to DNN core. If, however, you don't have it you can easily employ JavaScript "closure" as shown here (only 8 lines of JS):

-CLICK HERE TO NAVIGATE TO THE LINK-
http://www.eguanasolutions.com/DNN_Blog/EntryID/4.aspx

Using closure, you can drop your script anywhere you like in your skin or DNN site (even in a DNN module's standard HEADER or FOOTER setting) and it will always work.

(If you have jQuery, though, use that!)

Related Posts with Thumbnails

Recent Comments

Free DotNetNuke Stuff

Free DotNet Videos

  © Blogger template The Professional Template by Ourblogtemplates.com 2008

Back to TOP