Revolution X

Coding Community => Tutorials => Topic started by: Celebrus on May 27, 2009, 12:07:45 pm



Title: Identifying and manipulating elements using jQuery
Post by: Celebrus on May 27, 2009, 12:07:45 pm
Lets begin with this: What is jQuery?

From the jQuery website,
Quote
jQuery is a new type of JavaScript library.
Quote
jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way that you write JavaScript.


- I like to describe jQuery as this really cool javascript library that is here to make your life easy. What you can do with plain old javascript in 20 lines can be done by jQuery in 10 lines, maybe even lesser.

- jQuery has an interesting concept called chainability.

Code:
$("#something").addClass("smalltext").removeClass("largetext").show();
That one line of code finds elements that have the ID 'something', adds the class 'smalltext' to them, removes the class 'largetext' from them and then shows them if they are hidden. Interesting, huh?

- jQuery also has a number of awesome effects. Now you can use awesome animations to show hidden text without programming a single line extra.

- jQuery also has a very nice method of detecting events.

Code:
<script>
$("a").click(function(){
alert("You clicked a link!");
});
</script>
That code, placed in your headers, will alert the user whenever a link is clicked. (Annoying, I know.) That comes in very handy if you are trying to have clean HTML script with all your javascript in one single place.

Enough intro for now, so lets get started with the actual tut. 8)



This tutorial assumes that you have some basic knowledge of HTML. If you don't know HTML, don't worry. It's no biggy. Here are some links that are sure to help you out:
- w3schools (http://w3schools.com/html/default.asp)
- Cedge's HTML Cheat Sheet (http://cedesign.net/help2j.htm)


We all know what an element is – and this tutorial will teach you how to identify and manipulate them, in jQuery.

jQuery and CSS identify elements in the same way. If you know CSS, great! It'll be easier for you. Let's start with an example HTML document.

Code:
<html>
<head>
<title>Hi.</title>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
</body>
</html>


You probably know that all scripts go within script tags.

Code:
<script type="text/javascript">

</script>

Now put in a jQuery include. For our purposes, you can put in this:
Code:
<script src="http://9861.smfforfree4.com/jquery.js" type="text/javascript"></script>
 

NOTE: Do not use that in any page you publish. Download the latest jQuery from jquery.com and upload that to your hosting and use it from there.

You have to put that in your head section.

Code:
<html>
<head>
<title>Hi.</title>
<script src="http://9861.smfforfree4.com/jquery.js" type="text/javascript"></script>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
</body>
</html>

Lets try to isolate the ‘Hi there' text first.

This is the code you need:
Code:
$("h1")

Easy, eh? Now to see if that works, lets do something to it. If you put a ‘.hide()' after it, you get:
Code:
<script>
$("h1").hide();
</script>
 
Put that into the document somewhere after the h1 tag, save it and run it. Can you see the contents of h1? If you can, you have done something wrong. Repeat all the steps and try again. I'll explain later why it should be after the h1 tag.
This is what you should have:
Code:
<html>
<head>
<title>Hi.</title>
<script src="http://9861.smfforfree4.com/jquery.js" type="text/javascript"></script>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
<script>
$("h1").hide();
</script>
</body>
</html>
That was pretty easy, wasn't it? Now lets hide the bold stuff.

Code:
<script>
$("b").hide();
</script>

Put that in and try.
But, what if we had two bold elements and wanted to hide only one?
What if this is your document?
Code:
<html>
<head>
<title>Hi.</title>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
<i>I am learning jQuery!</i>
<b>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas metus nisi, euismod vel, mattis eu.</b>
</body>
</html>

OK, we want to hide the second one. How?
Answer: Give it an id.
Lets give it the ID “Lorem".
So this is our document now:
Code:
<html>
<head>
<title>Hi.</title>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
<i>I am learning jQuery!</i>
<b id="lorem">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas metus nisi, euismod vel, mattis eu.</b>
</body>
</html>

Then to hide it, you'd have:
Code:
<script>
$("b#lorem").hide();
</script>

Understood? We affix the id after a ‘#'.

Put that after the bold text and try. It should work.

There are another two methods: using the contains function and using a class.
Lets see how to use a class first.

Let's give the part to hide a class. Classes are usually used by CSS to give an element specific properties. Of course, no one's saying that you can't use IDs in CSS but the general practice is to use classes. This should be the HTML document.
Code:
<html>
<head>
<title>Hi.</title>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
<i>I am learning jQuery!</i>
<b class="lorem">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas metus nisi, euismod vel, mattis eu.</b>
</body>
</html>

As you can see, the lorem ipsum dolor paragraph now has a class, ‘lorem'. Now to hide it, you'd have
Code:
<script>
$("b.lorem").hide();
</script>
It's almost the same as the thing we did for using and id. This time we used a ‘.' Instead of a ‘#'.  Put it just before the </body> and try.


Now consider this document:
Code:
<html>
<head>
<title>Hi.</title>
</head>
<body>
<h1> Hi there </h1>
<h4>Welcome to my site</h4>
<b> Enjoy yourself </b>
<i>I am learning jQuery!</i>
<b>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas metus nisi, euismod vel, mattis eu.</b>
</body>
</html>

It's the same except that the lorem part doesn't have any class or ID. We will be using ':contains' to identify it.
This is the code you have:
Code:
<script>
$("b:contains('lorem')").hide();
</script>
That should be easy. Put it before the '</body>' and try.


Now lets look at another method of identifying a nested element.
Consider this HTML document.
Code:
<html>
<head>
<title>Hi again.</title>
</head>
<body>
<h1>The page</h1>
<div class="wrapper">
Click <a href="#somewhere">here</a>.
</div>
<div id="somewhere">lol</div>
</body>
</html>

We want to hide the link. It contains the text 'here'.

To hide it, you have
Code:
<script>
$("div.wrapper a").hide();
</script>

That code looks for an element that is an 'a' within a div having the class 'wrapper'. But what if there were 2 'a's within div.wrapper?
We will need to add something that gets only the anchors which link to #somewhere.

Code:
<script>
$("div.wrapper a[href='#something']")
</script>

Geddit? The thing in the [square] brackets? Basically, that makes it match only the elements with the property 'href' that is exactly the same as the string '#somthing'.
Try it. :)

Some theory on that:
[attribute]    
Matches elements that have the specified attribute.
[attribute=value]    
Matches elements that have the specified attribute with a certain value.
[attribute!=value]    
Matches elements that don't have the specified attribute with a certain value.
[attribute^=value]
Matches elements that have the specified attribute and it starts with a certain value.
[attribute$=value]    
Matches elements that have the specified attribute and it ends with a certain value.
[attribute*=value]
Matches elements that have the specified attribute and it contains a certain value.

What we did up there was the second one. I got that straight from the jQuery documentation. That ends the selecting part of this tutorial. To learn further, go here (http://docs.jquery.com/Selectors).

Now lets begin with manipulating elements. You already know how to hide stuff. Let's go deeper. ;)

I'll split this section into parts.

I. Inserting inside

We'll look at two things here - appending and prepending.

1. Appending
This is used to add some text at the end of all matched elements.

For example,
Code:
$("div.wrapper").append("<b>Hello!</b>");
will add Hello! at the end of divs that have the class 'wrapper'.

2. Prepending

This will add something to the beginning of matched elements.

Example:
Code:
$("div.wrapper").prepend("<b>Hello!</b>");
will add Hello! at the start of divs with the class 'wrapper'.

II. Hiding, Showing and Toggling


1. Hide

We already know what this does, no need to repeat.

Code:
$("#something").hide();
will hide all elements with the id '#something'.

2. Show
Will display hidden elements.

Code:
$("#something").show();
will show the #something that we hid above. ;)

3. Toggle
Will toggle elements. Which is to say, if it is hidden, it will show the element and if it is visible it will hide the element.

Code:
$("#something").toggle();


III. Changing contents

1. HTML
Used to set the HTML inside matched elements to something else.

Code:
$("#something").html("<b>Hello!</b>");

2. TEXT
Used to Set the text contents of all matched elements.

Code:
$("#something").text("HTML will not work here.");

Another example:

Source Code
Code:
$("p").text("<i>Some<i> <b>thing</b>");
Result:
Code:
<i>Some<i> <b>thing</b>


For more information on jQuery manipulation, go here (http://docs.jquery.com/Manipulation).

I promised to tell you why you have to put the code after the element you are trying to identify and manipulate. This is the reason: code is executed the moment it is downloaded, and if the code is below it, it is downloaded later and so the code can not find it at that time. Here is a way around that: put your code in this:
Code:
<script>
$(document).ready(function(){
// Code here
});
</script>

That will make the code execute only after the whole document has loaded.