Presentation is loading. Please wait.

Presentation is loading. Please wait.

Changing HTML Attributes each() function Anonymous Functions $(this) keyword.

Similar presentations


Presentation on theme: "Changing HTML Attributes each() function Anonymous Functions $(this) keyword."— Presentation transcript:

1 Changing HTML Attributes each() function Anonymous Functions $(this) keyword

2 Learning Objectives By the end of this lecture, you should be able to: – View and/or change HTML attributes using the ‘attr()’ function – Understand how the ‘each()’ function works – Apply a series of commands to a selector using an anonymous function with the each() function – Understand how the ‘this’ keyword works – Recall how to use variables for holding both numbers and strings – PUT IT ALL TOGETHER!

3 Review: Reading/Changing HTML Attributes In a previous discussion, we talked about reading and changing CSS properties using the css() function. Not surprisingly, jQuery also gives us a way to modify HTML attributes. Recall how the css() function lets you both check and add a property. For example: $('#random_text').css('font-family'); //will RETURN the name of the font of the ‘random_text’ ID $('#random_text').css('font-family', 'Verdana'); //will SET the font of ‘random_text’ ID to ‘Verdana’ Similarly, we have a function called attr() that allows you to either read or set the value of an HTML attribute. If you pass only the attribute name, the function will read (and return) the value of that attribute. If you pass a second argument, the function will set the attribute to the second argument: For example, suppose you have an image with an ID (not a filename!) of ‘firetruck’ $('#firetruck').attr('height'); //Will return the value of the ‘height’ attribute //If there is no height value set, the function returns ‘undefined’ $('#firetruck').attr('height', '200px'); //Will SET the value of the ‘height’ attribute to 200 pixels

4 Removing HTML Attributes We can remove an HTML attribute using the function: removeAttr() Suppose that for whatever reason, you wanted to remove the ‘alt’ attribute from all of your images. You can easily do so via: $('img').removeAttr('alt');

5 Selecting ALL items: the each() function API for the each() function: http://api.jquery.com/each/http://api.jquery.com/each/ Sometimes we want to operate on an entire group of items, such as every image in a section (or on the entire page). However, beyond simply chaining one or more jQuery functions, we sometimes want to do more elaborate scripting work on every item in the group. To apply one or more commands to multiple items on a page, you begin with your selection, and then invoke the each() function. The argument to the each() function is typically another function. I realize this is confusing, so we’ll go through it carefully. First let’s consider a task we might want to do to a group of images: Suppose we had a group of images on your page that we wanted to turn into thumbnails (small versions of the image). For every image on the page we might want to: 1.Reduce the height 2.Reduce the width 3.Include the words ‘Thumbnail of’ to the alt attribute Let’s pretend that we have just created a function to do all of these things,. We would then pass the code of this entire function as the argument to the each() function. In other words, we will copy and paste the entire code for this function INSIDE the parentheses like so: each ( _____________________ ) But the weirdness isn’t over yet : We will NOT give this function a name! Instead we will simply use the keyword function() $('img').each( function() { code goes here... } ); I do realize that this can easily be accopmlished by simply chaining three jQuery functions together! However, for demonstration purposes, we will use the each() function to accomplish the same task.

6 Anonymous Functions An anonymous function is simply a function that does not have a name. It is typically intended to be a function that is used only one time. If you don’t intend to invoke that function at any other point in your program/page, you should probably create an anonymous function. An anonymous function has the identifier (name), function(). A very simple anonymous function might look like this: function() { alert('An image was found'); }

7 Example of an Anonymous Function using the each() function Let’s begin with a simple example that simply outputs the string “An image was found” every time we find an image on the page. We will begin by setting up our so-called “anonymous function” as the argument to the each() function: $('img').each( function() { } ); Now let’s go ahead and write some code within the body of our anonymous function: $('img').each( function() { alert('An image was found'); } ); Let’s place this code inside our document.ready() function. Recall that document.ready() function executes automatically after the entire page has been loaded: $(document).ready(function() { $('img').each ( function() { alert('An image was found'); } ) ; } //close the anonymous function ); //close the ‘ready()’ function As always, TRY IT!!!Take a simple practice page that has a couple of images tags on it such as the page_of_stuff.htm file I have provided for you on the class web page. If you place this code on that page, then every time an image tag is found on the page, this alert box will pop up.

8 Anonymous Functions Let’s take a moment to discuss anonymous functions. When the argument to a function is itself a whole other function, we sometimes create something called an anonymous function. An anonymous function is a function that has no meaningful name. The identifier (name) we give to an anonymous function is always the same: it is simply called ‘ function() ’. Recall that the argument to the each() function is frequently an anonymous function. Therefore, it will look something like this: $('img').each ( function() { // Your code for this anonymous function will go in here. } //end of anonymous function ) ; //end of 'each()' function Pay VERY close attention to the various parentheses and braces and so on that I have carefully color-coded for you. If you don’t keep careful track of these, you can run into some debugging nightmares! (In fact, programmers often include comments at the end of each block to make it abundantly clear exaclty which brace/bracket is being closed. ) For this reason, you should ALWAYS start by placing all parentheses and braces in at the beginning – that is, before writing any of the actual code. In other words, start by typing ONLY the code in red: $('selector').each( function() { //code for function goes inside this block }); // Note how the closing brace, parenthesis, and semicolon are all on the same line. This is fine!

9 What in the world is $(this) ??? The each() function works hand-in-hand with two important entities that you need to know about. 1.The first concept is the idea of ‘anonymous’ functions. We have just finished discussing these. 2.The second concept is the ‘ this ’ keyword. The ‘ this ’ keyword is a way of referring to the particular selector as you are looping through. For example, say you are using each() to iterate through all of the images in your page. The ‘ this ’ keyword is a way of referring to the particular image that you are currently working with. So the first time an image is found, then ‘ this ’ refers to that particular image. When we loop around and get to our second image, then ‘ this ’ refers to that second image. When we loop again and are working with our third image, then ‘ this ’ refers to that third image. And so on… It is VERY important that you understand how to use the ‘ this ’ keyword. EXAMPLE: Here is some code that will find every image on the page and determine it’s filename by looking up the value of the ‘src’ attribute. Note how we use ‘this’ to refer to the current image. $('img').each ( function() { var currentImageName = $( this ).attr('src'); alert(currentImageName); });}); As you can see, each time we find an image, we look up it’s file name and store it in a variable called ‘ currentImageName ’. We then output that string inside an alert box. Now that we know about both anonymous functions and the ‘ this ’ keyword, let’s put it all together!

10 Accomplishing a group of tasks using the each() function The each() function is great when you have a series of commands you want to perform on a given selector for every occurrence of that selector on your page. Suppose we had a group of images on your page and we wanted to turn ALL of them into thumbnails (small versions of the image). So for every image on the page we want to: 1.Reduce the height 2.Reduce the width 3.Include the string ‘Thumbnail of’ to the beginning of the alt attribute Here is the the code that will do so. $('img').each(function() { $(this).attr('width','50px'); //change the ‘width’ attribute to 50 pixels $(this).attr('height','50px'); //change the ‘height’ attribute to 50 pixels //Change the alt attribute to begin with the string: "Thumbnail of": //First we retrieve the current value of the alt attribute and store it in a variable var currentAlt = $(this).attr('alt'); //We then CONCATENATE the string "Thumbnail of " and the current alt value together: currentAlt = "Thumbnail of " + currentAlt; //Now we take this new string ‘currentAlt’ and assign it as the value of the ‘alt’ attribute $(this).attr('alt',currentAlt); }); //end of anonymous function and of each() function See file: each_anonymous_function.htm

11 Example: Counting Paragraphs Okay, so this won’t be the most exciting example in the world, but it will serve both as another example of using the each() function and also as a review of how to use a counter. (Counters are HUGELY important in programming). In this example, as soon as the page finishes loading (i.e. using the document.ready() function), we will write some code that will count the number of paragraphs (‘p’) tags and output the result to an alert box. Here is the code: $(document).ready(function() { var numberOfParagraphs=0; $('p').each( function() { numberOfParagraphs=numberOfParagraphs+1; }); //end each() function alert("There are " + numberOfParagraphs + " paragraphs."); }); //end ready() function In this example, we create a variable to keep track of the number of paragraphs and initialize it to 0. We then iterate through every ‘p’ tag on the page. Each time we find a ‘p’ tag, we go through the code inside the anonymous function. This code says to take the numberOfParagraphs variable and increase it by 1. Once we have finished iterating through every instance of the ‘p’ selector, we exit the each() loop and simply output the result.

12 Pop-Quiz $(document).ready(function() { var numberOfParagraphs=0; $('p').each( function() { numberOfParagraphs=numberOfParagraphs+1; }); //end of the each() function alert(numberOfParagraphs); }); //end of the ready() function 1.QUESTION: In the counting-paragraphs example, why did we declare and initialize the ‘ numberOfParagraphs ’ example OUTSIDE of the each() loop? 2.QUESTION: Similarly, why did we place our alert() statement outside of the each() loop? Answer 1: If we had placed the ‘ numberOfParagraphs=0 ’ inside the each() loop, then every time we went through the loop, we would reset the value of the variable to 0! Answer 2: Had we placed the ‘ alert(numberOfParagraphs) ’ inside the loop, then we would have outputted an alert statement every time through the loop! If we had 20+ paragraphs in our page, this would quickly become very annoying!

13 Example: Listing all the images See file: list_of_images.htm Suppose we had a series of images on a page. At the end of the page, we would like to create a list (‘ul’) of all of the images based on their ‘alt’ attributes. Here is the relevant code: var listOfImages = ""; //create an empty string $('img').each( function() { //retrieve the value of the 'alt' attribute //and store it in the variable 'currentImageAlt' var currentImageAlt = $(this).attr('alt'); //concatenate a before and a after the currentImage variable listOfImages = listOfImages + ' ' + currentImageAlt + ' '; }); //end of each() //We now have out list! Let’s output it using document.write() //REMEMBER: Always try to put document.write statements //at the END of your page. document.write(' Here is a list of the images on this page: '); document.write(' ' + listOfImages + ' '); document.write(' Goodbye!! ');

14 Reminder: “Rendered” Source Code Recall how when you use ‘View Source’ in your typical browser, you only see the original source code of the document. For example, if you tried to view the source of the file list_of_images.htm just demonstrated, you would not see any of the HTML list that was generated by our scripts. In order to view the ‘final’ version of the code, you want to look for an option in whichever debugger or editor you are using (e.g. Firebug) called something along the lines of “rendered” code. Different editing tools will have different names. But nearly all of them do offer this option.


Download ppt "Changing HTML Attributes each() function Anonymous Functions $(this) keyword."

Similar presentations


Ads by Google