Dec 10 2009

JQuery Part 4 – Intro to CSS Manipulation

JQuery is often used in websites to manipulate the CSS attributes of an HTML element upon the users request. For example, if a user wants to increase the size of the font immediately so that they can read your page, or you may just want to change up the CSS on the fly to make your page stand out a little more. All these things can be done in JQuery using the css() function and css manipulation techniques. Let’s get started by creating a basic page with a link and a paragraph with some links in it like so…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>
	<head>
		<script src="lib/jquery/jquery-1.3.2.js" type="text/javascript"></script>
 
		<title>JQuery CSS Manipulation</title>
 
	</head>
	<body>
		<a href="#">Click Me</a>
 
		<br>
			<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam sit amet elit vitae arcu interdum ullamcorper. Nullam ultrices, nisi quis scelerisque convallis, <a href="#">augue neque</a> tempor enim, et mattis justo nibh eu elit. Quisque ultrices gravida pede. Mauris accumsan vulputate tellus. Phasellus condimentum bibendum dolor. Mauris sed ipsum. Phasellus in diam. Nam sapien ligula, consectetuer id, <a href="#">hendrerit</a> in, cursus sed, leo. Nam tincidunt rhoncus urna. Aliquam id massa ut nibh bibendum imperdiet. Curabitur neque mauris, porta vel, lacinia quis, placerat ultrices, orci.</p>
 
	</body>
</html>

As you can see it’s a basic HTML page that references the JQuery script. We have also added a link that says “click me” along with a paragraph of lorem ipsum text with some links in it. Alright, now onto creating the CSS for the page. For this example I will be putting the CSS in the header but if you want to put it in an external file by all means go ahead and reference it in the header.

<style type="text/css">		
p a
{
	color: red;
}
</style>

As you can see, I just added an attribute to make all the links within the paragraph tags initially turn up as red. You can add as many CSS elements here as you would like to style the links however you like but for the purpose of this demonstration you will just need the color red as an attribute. Next let’s add the JQuery and introduce the .css() function.

<script type="text/javascript">
	$(function()
	{
		$('a').click(function()
		{
			$('p a').css('color', 'blue');
		});
	});
</script>

As you can see the JQuery code is pretty straight forward for what we’re doing. Basically we’re starting out by checking the DOM to make sure that the file is ready to be manipulated. Then, we perform a click function anytime an anchor tag is pressed. Inside of that click function is where we actually manipulate the CSS and change the color of the anchor tags to blue instead of red like we originally set. The css() function accepts two parameters that we’ll be using. The first is the attribute that you would like to change and the second is the attribute that you want to change it to. So for our example, the attribute is the color and we’re going to change it to blue. If of course you want to change the color of the link that was originally pressed instead of every link inside the paragraph tags you could use the “this” function instead of specifying a specific tag.

That’s the basics to CSS manipulation using JQuery, of course the example shown here is only a very basic example and can be greatly expanded upon. This is what the final code should look like…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>
	<head>
		<script src="lib/jquery/jquery-1.3.2.js" type="text/javascript"></script>
 
		<title>JQuery Test</title>
 
		<style type="text/css">		
			p a
			{
				color: red;
			}
		</style>
 
		<script type="text/javascript">
			$(function()
			{
				$('a').click(function()
				{
					$('p a').css('color', 'blue');
				});
			});
		</script>
	</head>
	<body>
		<div id="box"></div>
		<a href="#">Click Me</a>
		<br />
			<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam sit amet elit vitae arcu interdum ullamcorper. Nullam ultrices, nisi quis scelerisque convallis, <a href="#">augue neque</a> tempor enim, et mattis justo nibh eu elit. Quisque ultrices gravida pede. Mauris accumsan vulputate tellus. Phasellus condimentum bibendum dolor. Mauris sed ipsum. Phasellus in diam. Nam sapien ligula, consectetuer id, <a href="#">hendrerit</a> in, cursus sed, leo. Nam tincidunt rhoncus urna. Aliquam id massa ut nibh bibendum imperdiet. Curabitur neque mauris, porta vel, lacinia quis, placerat ultrices, orci.</p>
	</body>
</html>

Oct 31 2009

JQuery Part 3 – Intro to Functions

This is part 3 in a series of JQuery tutorials. I strongly recommend at least reading Part 1 before continuing with this tutorial. Part 2 is optional but would also be a great background before we get started. As for this tutorial, I will be going over creating an executing functions to make your code more efficient.

Often when writing JQuery code(especially for plugins) there are times when you need to execute the same block of code multiple times. Instead of writing them all out individually and making our code really terrible process wise, we can use functions and function calls to call the same block of code over and over.

Creating Functions

You can create a function in 2 different places. The first is in the same script tags, but not inside the document ready function. Or second, you could create a brand new script file and then reference that script file in your header. Inside this script file you could create your method and it would be able to be accessed by the main file.

To create a function, the syntax looks like this…

function nameOfFunction()
{
	//your code here
}

This tells the browser that there is a function called nameOfFunction that is not being passed any parameters. Passing parameters is something I’ll get into a little bit later. Now say you wanted to alert the user with a javascript pop-up box every time this function was run. You could add some code into the function to allow a dialog box to appear like so.

function nameOfFunction()
{
	alert("We are now alerting the user!");
}

Executing Functions

Now that we have a function created, we need to somehow call that function to execute. That’s where our javascript method calls come in. Let’s say we wanted to execute the previous function. The code would look like this.

$(document).ready(function(){
	nameOfFunction();
});

Of course this would call the function immediately after the page was ready. You can use a function call in JQuery in any function. So if you wanted to add it inside of a .click function you could do that as well. That’s all you need to do to execute functions in JQuery.

Passing Arguments to Functions

Let’s say you wanted a function to work with a piece of data from a form, but you didn’t want the function to retrieve that piece of data inside the function. You can use a piece of code called an argument to pass to the function. This allows you to pass values to a function so they can be used. To create a function with an argument then all you need to do is add the argument into the brackets in the function header. It looks like this.

function nameOfFunction(argument)
{
	//your code here
}

Now obviously since we have that argument in the argument ready to do something with it, we may also want to return a value back to the original function so that we can maybe display the result of a calculation or something like that. If we want to return a value all we have to do is insert a return value into our function.

function nameOfFunction(argument)
{
	var total = 10 + argument;
 
	return total;
}

This function will now accept a value, add 10 to that value and return it to the original function call. This way if we need to manipulate some data quite a few times, we could use a function to do that display the result.

Function Calls with Arguments

Now that we have a function made that’s accepting an argument and returning a value, we can use a function call and pass an argument to the function so it can do the calculation and we can then display the result. The function call looks something like this.

$(document).ready(function(){
	alert("The total is = " + nameOfFunction(10);
});

In our JQuery ready function we are now just displaying an alert. Inside the alert we are actually making the function call and passing a value of 10 to our function. The function is then going to add 10 to our passed argument and return a value of 20. The alert therefore is going to display – “The total is = 20″. And that’s all for basic functions and function calls.


Oct 29 2009

JQuery Part 2 – Basic Animation

Welcome to JQuery part 2, using basic animation techniques. You should already have a basic understanding of JQuery and it’s elements to complete this tutorial. If you don’t, please refer to my JQuery Introduction post found here. Now to get started…

Let’s start by creating a basic HTML page and call it index.html in the root of our web servers directory and add a basic page structure to that file. Let’s also make sure that we have the JQuery libraries imported and ready to use.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>JQuery Animations</title>
 
		<script type="text/javascript" src="lib/jquery.js" />	
 
	</head>
	<body>
	</body>
</html>

Now, in order to complete animation we will need to display an element to animate. The easiest way to do this is to use some basic CSS. So for the purpose of this tutorial let’s create a style.css file and put it in the root of our directory. Let’s then link it to our index.html file so that we can use it.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>JQuery Animations</title>
 
		<script type="text/javascript" src="lib/jquery.js" />
 
		<link rel="stylesheet" href="style.css" type="text/css" />
 
	</head>
	<body>
	</body>
</html>

Now that we have our CSS file linked to our HTML we’re going to need to add an element to animate. For this demonstration we’re just going to use a red box that’s 100px by 100px inside a div. Let’s add that to our CSS file.

#redBox
{
	width:100px;
	height:100px;
	background-color: red;
}

Now we’ll add the appropriate div tags to our HTML file so that our red box shows up. We’re also going to add an anchor tag directly below our red box to toggle the box between showing and disappearing.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title>JQuery Animations</title>
 
	<script type="text/javascript" src="lib/jquery.js" />
 
	<link rel="stylesheet" href="style.css" type="text/css" />
 
</head>
	<body>
		<div id="redBox"></div>
		<a href="#">Show/Hide</a>
	</body>
</html>

Now we’re all ready to start coding our JQuery. If you run the HTML file right now you should see a red box sitting at the top left hand corner of the page. Right now the red box shouldn’t do anything as we haven’t coded the JQuery. So let’s start out by using the document ready function. and adding a function to all of our anchor tags.

<script>
	$(document).ready(function(){
		$('a').click(function({
 
		));
	});
</script>

Now we’re ready to be using some of the animation methods found in the JQuery library. First, since the box is by default showing up in the browser we’re going to make it hide by using the .hide() function. The .hide() function can be used without any parameters being passed or you can pass a speed and an optional callback(). The callback is a function to be executed when the animation has been completed. For the sake of this tutorial we’re only going to cover the speed parameter.

<script>
	$(document).ready(function(){
		$('a').click(function({
			$('#redBox').hide('slow');
		));
	});
</script>

Now, if you include the script section in the header of your index.html document and run it, when you click the anchor tag you should see the red box that we created disappear. However now the red box is gone and we can’t get it back. We’re going to need to change this so that we can get it back by clicking on the anchor tag again. In order to get this we’re going to need to add another function and pass it as a parameter to our .click() function for our anchor tags.

<script>
	$(document).ready(function(){
		$('a').click(function({
			$('#redBox').hide('slow');
		},function(){
			$('#redBox').show('slow');
		});
	});
	</script>

Since we’re adding the new function as another parameter to the click function, we need to terminate the current function before starting the new one. This is why we need to close the curly braces from the previous function before we start another. If we didn’t close the curly braces and just put it inside the first function then every time we clicked on the anchor tag, it would disappear and then show again without pressing the anchor tag. Now when we put that all together and run it, whenever we click the anchor tag the box should disappear and then re-appear when we click it again. Here is the complete code.

<html>
<head>
	<title>JQuery Animations</title>
 
	<script type="text/javascript" src="lib/jquery.js" />
 
	<link rel="stylesheet" href="style.css" type="text/css" />
 
	<script>
	$(document).ready(function(){
		$('a').click(function({
			$('#redBox').hide('slow');
		},function(){
			$('#redBox').show('slow');
		});
	});
	</script>
 
	</head>
	<body>
		<div id="redBox"></div>
		<a href="#">Show/Hide</a>
	</body>
</html>

In the tutorial I just used 2 of the more basic animation functions in the JQuery library. For a full reference to the JQuery animation API, please check out http://docs.jquery.com/Effects/. Stay tuned for JQuery part 3 :D .


Oct 28 2009

Introduction to JQuery: Part 1

JQuery is a javascript library that simplifies javascript’s interaction with HTML to speed up javascript coding.

Benefits of JQuery

- Lightweight Footprint
- CSS3 Compliant
- Cross-Browser compatibility

What you will need

- Javascript enabled browser
- JQuery Library
- An application to code in(Coda, Aptana, or even notepad)

Starting out

To start out coding with the JQuery library you will need to import the library. Usually I like to structure my site with a /lib folder at the root of the directory. This way I can include all of my javascript libraries in one central location so they don’t replicate down the road. So for this project i’ll setup my directory structure with my JQuery files inside the lib folder. Next we’ll create an index.html file inside the root directory. This will be our testing file for our JQuery code. Alright, let’s get started, let’s start by adding a basic page structure to your index.html file.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>JQuery Test</title>
	</head>
	<body>
	</body>
</html>

Next we need to add in our JQuery script so that we can use it. Add in the following code inside your header tags. Use the src tag to point to your JQuery javascript file.

<script type="text/javascript" src="lib/jquery.js" />

Making Sure the document is ready

First off, any JQuery code that we want to include goes into script tags. This is because JQuery runs on top of javascript, so in order for the browser to understand what JQuery is doing, it needs to be included inside the script tags.

Now, the first thing that we need to do is make sure that the document is ready to be used. We do this to make sure that no changes occur before the user is ready to see it. So if the page isn’t loaded or the user is on a slow connection, the JQuery code will not start executing until the document is loaded and ready. To do this we use the document ready function in JQuery.

<script>
$(document).ready(function(){
});
</script>

Adding a click event to a link

Now that our document is ready for our JQuery code we can add some functionality to our site. The first thing we’ll deal with is adding a link to our index.html file. That way we have something to manipulate when we go to code our JQuery. Let’s add a link to our index.html file now.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>JQuery Test</title>
 
		<script type="text/javascript" src="lib/jquery.js" />
 
	</head>
	<body>
 
		<a href="http://www.google.ca/">Link</a>
 
	</body>
</html>

Once we have our link added we can start to code the JQuery. What we’re going to do in this instance is instead of taking the user to google, we’re going to just display a simple javascript alert instead.

<script>
	$(document).ready(function(){
		$('a').click(function({
			alert("Obviously you're still here and not over at google");
			event.preventDefault();
		));
	});
</script>

Alright, so that probably looks a little confusing right off the bat, especially if you’re used to regular javascript coding. Let’s break it down into a little more detail. To start off, $(’a'). This means that we’re taking the element “a” from the html. If we wanted to use the id of say a form(id=”test”) then we could just do $(’#test’) instead. Then after we have a function. This will allow us to do something with the element that we retrieved from the HTML. In this case, we’re going to use the “.click()” function to allow us to process an event when any element with an attribute of “a” is clicked. Now because we want to do something with that event whenever it’s clicked, we can use a function inside of the click function. That’s where the .click(function(){}) section comes from. Now in order to actually accomplish something with the event that was created we need to put the rest of our code inside of the curly braces of the function. In this case we’re just creating a plain javascript alert box with a message in it. The next line, “event.preventDefault();” is just a function in JQuery that disables the default behavior of the element. In this case the default behavior is to send the user to google, so we’re going to make the user stay at our page and just simply display a javascript alert.

Since .click is a function we will need to close our the function using a “;”. That’s it, you just wrote your first function and created your first event. All together the code looks like this.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<title>JQuery Test</title>
 
		<script type="text/javascript" src="lib/jquery.js" />			
 
		<script>
			$(document).ready(function(){
				$('a').click(function({
					alert("Obviously you're still here and not over at google");
					event.preventDefault();
				));
			});
		</script>
 
	</head>
	<body>
 
		<a href="http://www.google.ca/">Link</a>
 
	</body>
</html>

For more information on JQuery or more tutorials you can visit the jquery site at http://jquery.com/. If you have any questions or comments feel free to leave a comment and I’ll respond as quickly as possible.

Cheers