MorkaLork Development

Interesting stuff I've picked up over the years...

Dynamically create elements with jQuery

2009-12-21 13:28:03 | 2354 views | jquery element elements create new dynamically

What do we want to do?


The point of this tutorial is to learn how to add a new html element to a webpage. This is an example of what we are going to do:

Start page:

<html>
<body>
</body>
</html>


Add a div:

<html>
<body>
<div>
</div>
</body>
</html>


We are going to use jQuery to create new elements and add them by using the built-in support in jQuery.
The first example will be a very basic one. We are going to create a link that, when pressed, will add a new paragraph to a div. It's quite short, and very simple, here's the code:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#myLink').click(function(){
var newParagraph = $('<p />').text("Goodbye world...");
$('#myDiv').append(newParagraph);
});
});
</script>
</head>

<body>
<div id="myDiv">
</div>
<a href="#" id="myLink">Change text</a>
</body>
</html>


This is the syntax to create a new object:

var newObject = $(name);

That's it. What we did here was that we created an empty paragraph ('<p />') and added some text to it. After that we just append the new object to whatever element should serve as parent.
We could actually shorten this down by using the appendTo() function:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#myLink').click(function(){
/*
var newParagraph = $('<p />').text("Goodbye world...");
$('#myDiv').append(newParagraph);
*/

$('<p />').text("Goodbye world...").appendTo($('#myDiv'));
});
});
</script>
</head>

<body>
<div id="myDiv">
</div>
<a href="#" id="myLink">Change text</a>
</body>
</html>


Now, as this is a follow up article, the examples in this article will continue on the started example index (in this case 6).

View example here.


Dynamically add textboxes to a form


In this next example we will let a user add more than one URL on a form. If the user wants to add another URL, we'll create a new input box for the user with its own unique ID, thus making us able to fetch it all with whatever server-side language we use.

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
var nextUrlId = 2;
$('#AddUrl').click(function(){
//Create and add a paragraph
$('<p />').attr('id', 'urlParagraph' + nextUrlId)
.text("URL: ")
.appendTo('#inputBoxes');

//Create and add an input box
$('<input />').attr({'type':'text', 'id':'url' + nextUrlId})
.appendTo('#urlParagraph' + nextUrlId);

//Iterate id number
nextUrlId++;
});
});
</script>
</head>

<body>
<form id="myForm" action="somePage.php" method="get">
<div id="inputBoxes">
<p id="nameParagraph">Name: <input type="text" id="name" /></p>
<p id="urlParagraph1">URL: <input type="text" id="url1" /></p>
</div>
<p><input type="submit" id="submit" /> or <a href="#" id="AddUrl">Add another URL</a></p>
</form>
</body>
</html>


View example here.

What we do here is basically the same as before. We create a new paragraph for the form and then add an input box to that paragraph. Since we need to have unique ID's for all input boxes (in order to get the result on the server side) we have to keep a variable containing the current ID iterating.


Dynamically add to a table


I will just show you another example of how to add things dynamically. You might often need to add data to a table, using jQuery rather than reloading the page makes it easier for a user to deal with your page:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
var rowNumber = 0;
$('#AddResults').click(function(){
//Get the user input
var nameInput = $('#nameInput').val();
var urlInput = $('#urlInput').val();

//Create a new row with an ID
var newRow = $('<tr />').attr('id', 'row' + rowNumber);
//Add some HTML to the row
newRow.html('<td>' + nameInput + '</td><td>' + urlInput + '</td>');

//Append the new row to the body of the #myTable table
$('#myTable tbody').append(newRow);

//Iterate row number
rowNumber++;
});
});
</script>
</head>

<body>
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>URL</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p>Name: <input type="text" id="nameInput" /></p>
<p>URL: <input type="text" id="urlInput" /></p>
<p><a href="#" id="AddResults">Add</a></p>
</body>
</html>


View example here.


Problems with dynamically created elements


There is a tiny problem with creating elements after the DOM has been loaded. An event bound to say a paragraph click ($('p').click(function(){});) will not fire when an element that wasn't created initially calls.
That is, if I create a new paragraph after the page has been loaded, using the technique from above, nothing will happen when I press it.
This is most troublesome, but fortunately there is a cure; live().
The live event will bind a handler to an event (such as our newly created paragraph to the p.click() event). How it works is best explained on jquery.com in this article.
The live event currently supports the following event values:


It does not support the following events:


So, how do we use the live event? Let's move back to our initial example (with some modifications):

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#myLink').click(function(){
$('<p />').text("Goodbye world...").appendTo($('#myDiv'));
});

$('p').click(function(){
alert("This paragraph has the following text:\n" + $(this).text());
});
});
</script>
</head>

<body>
<div id="myDiv">
<p>Hello world!</p>
</div>
<a href="#" id="myLink">Add new paragraph</a>
</body>
</html>


View example here.

If you run this example and press the first paragraph you will get an alert box that says "This paragraph has the following text: Hello World!".
That's great.
But what if we use our link to add another paragraph? Well, we'll get a new paragraph with the text 'Goodbye world...', but if we click it, nothing happens. That is because the click event only listens to the elements that originally existed in the DOM after loading. Our new paragraph has been added afterwards and thus is not bound the event.
If we however use the live event, we can get the click event to fire for all existing paragraphs AND all future ones too:

<html>
<head>
<!--Load the jquery lib -->
<script type="text/javascript" src="jquery-1.3.2.js"></script>

<!--Use jquery -->
<script type="text/javascript">
$(document).ready(function(){
$('#myLink').click(function(){
$('<p />').text("Goodbye world...").appendTo($('#myDiv'));
});

$('p').live("click", function(){
alert("This paragraph has the following text:\n" + $(this).text());
});
});
</script>
</head>

<body>
<div id="myDiv">
<p>Hello world!</p>
</div>
<a href="#" id="myLink">Change text</a>
</body>
</html>


View example here.

In this second example we can see that the newly created paragraphs are all bound to the click event, so all is well.

In conclusion, dynamically creating elements is quite simple using jQuery and can many times improve a visitors stay at your website.


Article comments

Feel free to comment this article using a facebook profile.

I'm using facebook accounts for identification since even akismet couldn't handle all the spam I receive every day.