Entries Tagged as 'jQuery'

Example of jQuery live()

Last week, I tweeted that I freaking love jQuery's live(). I meant every word too! It's really useful, especially when you're working with ajax. I got some responses on twitter, some people agreed and others weren't really sure where they would use it. So, I'd figure I'd provide an example.

With ajax, it's possible to return HTML to the calling page. Whether you prefer doing it or not, it's possible. Some people prefer to return JSON and build the appropriate HTML, some find it easier to return HTML to the server. Regardless, that HTML that is returned via ajax may or may not contain a link. The link itself may be requested to kick off some javascript function. The problem is, that HTML was loaded in after the fact and isn't necessarily bound to the existing DOM events already on the page.

Well, that's where live() comes in. So, let's start with this plain example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#test').before('<a href="#" class="button">This is a link</a>');
$('.button').click(function(){ alert('foo!'); return false; });
});
</script>
</head>
<body>
<p><a href="#" class="button">Test #1</a></p>
<div id="test"></div>
</body>
</html>

So, we're keeping this example simple. I have a static link on the page and you'll also see that I'm actually creating a link via jQuery and inserting the link before the <div id="test"></div>. Both links work and will alert foo! when you click it. No need for live() here yet. A live example of this can be found here.

I have a file called test.html that contains the following:

<br /><a href="#" class="button">Test #2</a>

So, let's modify our example code a little and pull this in:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#test').before('<a href="#" class="button">This is a link</a>');
$('.button').click(function(){ alert('foo!'); return false; });
$('#test').load('test.html');
});
</script>
</head>
<body>
<p><a href="#" class="button">Test #1</a></p>
<div id="test"></div>
</body>
</html>

Live example of the above code. So, we used jQuery's load() to go open test.html and inject the content of test.html straight into <div id="test"></div>. View the page. Click on the links and make sure you get an alert box from javascript saying, foo! Your third link failed didn't it? Why? Because that HTML that was pulled in via ajax wasn't part of the current DOM. You pulled that in after the fact and jQuery is unaware of it.

Let's go read the 1st sentence of live() again: Binds a handler to an event (like click) for all current - and future - matched element. So, by that statement, the HTML pulled from test.html is considered "future" elements. So, now it's time to go tell our time traveling element that it has a click event that it has to adhere to.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#test').before('<a href="#" class="button">This is a link</a>');
$('#test').load('test.html');
$('.button').live('click', function(){ alert('foo!'); return false;} ); // this line can be anywhere
});
</script>
</head>
<body>
<p><a href="#" class="button">Test #1</a></p>
<div id="test"></div>
</body>
</html>

Live example of the above code. Notice that we have changed our $('.button').click({ function here }); to $('.button').live('click',{ function here });. So now we have put an click event handler on our existing elements and our time traveling elements. Clicking on all links should now return foo! So, essentially, live() is a nice way of making sure that all current and future elements have event handlers on them. This can be used for any elements, not just links.

Hope this helps someone.

Do not fear the jQuery

Honestly, I can't remember what really hooked me into jQuery. I think it was a combination of messing with the Adobe ColdFusion 8 Ajax Tags, Reading Ben Nadel's numerous posts and scouring over the jQuery documentation.  I'm hoping that I can inspire people to just... play? That's all I did. Just monkey around with jQuery. Ask yourself simple questions such as, "How can I turn that div's background red?" Solve it and move on to the next question.

If you're a guru with CSS, jQuery practically basically begs you to learn it. 50% of the work in jQuery is figuring out the best way to set up the HTML page.

With that, a simple demo of sliding divs:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#stuff { display: none; margin: 2px auto; padding: 4px; border: 1px solid red; width: 60%; }
#content { margin: 2px auto; padding: 4px; border: 1px solid black; width: 60%; }
#closeme { float: right; }
a { text-decoration: none; }
</style>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
</head>
<body>
<div id="stuff"><a href="#" id="closeme">[X]</a> See? I'm a hidden div.</div>
<div id="content">This is the main content.<br /><br /><a href="#" id="reveal">Reveal div #stuff</a></div>
</body>
</html>

So, to keep this example simple, we're just going to start with this basic skeleton. You see 2 divs and if you correspond the div id with the css, you'll see that the <div id="stuff"> is set to display: none; This means it won't be rendered on the screen when you load the page. The main div of the page is <div id="content"> which has content inside, including a link.

You'll see that I'm using the Google API to host the jQuery .js file. This is me being lazy as I don't want to download the .js file -- I can just use google to host it for me.

Next step, we're going to add the document ready function -- what this does is tells jQuery not to run anything until the DOM is fully loaded.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#stuff { display: none; margin: 2px auto; padding: 4px; border: 1px solid red; width: 60%; }
#content { margin: 2px auto; padding: 4px; border: 1px solid black; width: 60%; }
#closeme { float: right; }
a { text-decoration: none; }
</style>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function(){
	// This is a javascript comment
	// This area is where our code will go.});
</script>
</head>
<body>
<div id="stuff"><a href="" id="closeme">[X]</a> See? I'm a hidden div.</div>
<div id="content">This is the main content.<br /><br /><a href="##" id="reveal">Reveal div #stuff</a></div>
</body>
</html>

I haven't actually added anything yet, but you'll see that I'm finally ready to add some jQuery code to make this all work. So, once the $(document).ready() is established, we need to figure out what we want. We want <div id="stuff"> to slide down when "Reveal div #stuff" is clicked.  We also want a "close" button, so the link with the id="closeme" will be our closer. When you click it, <div id="stuff"> should go back up and out of the way again.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#stuff { display: none; margin: 2px auto; padding: 4px; border: 1px solid red; width: 60%; }
#content { margin: 2px auto; padding: 4px; border: 1px solid black; width: 60%; }
#closeme { float: right; }
a { text-decoration: none; }
</style>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function(){
	$('#reveal').click(function(){
		$('#stuff').slideDown();
		return false;
	});
	$('#closeme').click(function(){
		$('#stuff').slideUp();
		return false;
	});
});
</script>
</head>
<body>
<div id="stuff"><a href="" id="closeme">[X]</a> See? I'm a hidden div.</div>
<div id="content">This is the main content.<br /><br /><a href="##" id="reveal">Reveal div #stuff</a></div>
</body>
</html>

So, let's break this down again. When our <a href="#" id="reveal"> is clicked ( $('#reveal').click() ) we want <div id="stuff"> to slide down. So we reference our <div id="stuff"> as $('#stuff') and .slideDown() is a native function in jQuery that tells a hidden element to slide down from the top ( $('#stuff').slideDown() ).  Return false is there to prevent the actuall page reload and to keep the anchor symbols from stacking up.

So, at this point, you should be able to follow along with the $('#closeme') and .slideUp() <div id="stuff">? If you did everything correctly, your demo should work like this.

So, Lola Lee Beno (aka LL Cool Beno) asked me on Twitter. How would you get it to slide down automatically? How would you? Everything you need to know is right on this page. You know that nothing happens until the document ready is fired (automatic event) and you know you want <div id="stuff"> to slide down.

Your final answer?