AndyJarrett

Creating a new DOM element with jQuery

I've been using jQuery for a while now keep meaning to blog about the little bits I use often. One is creating a DIV object on the fly and loading content in to it.$(document).ready(function(){ // Your URL of the page to be loaded u = "/index.cfm?event=contactme"; // We're creating a div element to load the URL contents into div = $("
"); // When the element is displayed at first we could leave it blank // or a loading image, or in this case the wording loading...... div.html("Loading......"); // We now load our file and inject it into the DOM. div.load(u); // With the DIV getting its content we need to put the DOM on the page // and in to the body. $.prepend will put our content at the top of // of the $("body").prepend(div);})Instead of having "Loading...." being displayed you can delay showing the content of the DIV until loading is completed. // Your URL of the page to be loaded u = "/index.cfm?event=contactme"; // We're creating a div element to load the URL contents into div = $("
"); // We now load our file and inject it into the DOM. div.load(u); // By default we're going to hide the DIV until the content is loaded div.hide(); // Before the DIV gets its content we need to put the DOM on the page // and in to the body. $.prepend will put our content at the top of // of the . But this will be hid. $("body").prepend(div); // Now we load the content into the DOM and as a CALLBACK function // we SLIDEDOWN the div. This could be FADEIN or something else. div.load(u, {limit: 25}, function(){ div.slideDown(); }); Both sets of code will load on document ready. Usually I tie this kind of process to a click event to load in a page dynamically when needed. Also don't forget you can chain these methods too and cut down on code. Taking the first example it could be written as: u = "/index.cfm?event=hermes.contactSeller"; div = $("
").html("Loading......").load(u); $("body").prepend(div); \n

\n

\n\n\n\n