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

Slides:



Advertisements
Similar presentations
Cascading Style Sheets
Advertisements

HTML Overview - Cascading Style Sheets (CSS). Before We Begin Make a copy of one of your HTML file you have previously created Make a copy of one of your.
Modifying existing content Adding/Removing content on a page using jQuery.
Events Part III The event object. Learning Objectives By the end of this lecture, you should be able to: – Learn to use the hover() function – Work with.
The Web Warrior Guide to Web Design Technologies
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
JQuery: Fun ‘n Games with Selectors. Learning Objectives By the end of this lecture, you should be able to: – Comfortably use jQuery to select based on.
Introduction to JavaScript for Python Programmers
Introduction to scripting
Random Stuff Colors Sizes CSS Shortcuts. Learning Objectives By the end of this lecture, you should be able to: – Identify the 3 most common ways in which.
CSS (Cascading Style Sheets): How the web is styled Create Rules that specify how the content of an HTML Element should appear. CSS controls how your web.
JQuery and Forms – Part I. Learning Objectives By the end of this lecture, you should be able to: – Retrieve the values entered by a user into a form.
Selectors. Learning Objectives By the end of this lecture, you should be able to: – Select items using jQuery based on ID, class name, or HTML tag. –
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
CSS Sprites. What are sprites? In the early days of video games, memory for graphics was very low. So to make things load quickly and make graphics look.
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
1 Essential HTML coding By Fadi Safieddine (Week 2)
Bill's Amazing Content Rotator jQuery Content Rotator.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
Client Scripting1 Internet Systems Design. Client Scripting2 n “A scripting language is a programming language that is used to manipulate, customize,
Unit 2, cont. September 12 More HTML. Attributes Some tags are modifiable with attributes This changes the way a tag behaves Modifying a tag requires.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Working with Files. Learning Objectives By the end of this lecture, you should be able to: – Examine a file that contains code with unfamiliar material,
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
Sahar Mosleh California State University San MarcosPage 1 JavaScript Basic.
ECA 225 Applied Interactive Programming1 ECA 225 Applied Online Programming basics.
JavaScript, Fourth Edition
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
JavaScript Defined DOM (Document Object Model) General Syntax Body vs. Head Variables Math & Logic Selection Functions & Events Loops Animation Getting.
Events Part I Mouse Events. Learning Objectives By the end of this lecture, you should be able to: – Understand what is meant by an ‘event’ – Appreciate.
IS2802 Introduction to Multimedia Applications for Business Lecture 07: Introduction to jQuery Rob Gleasure
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Functions.  Assignment #2 is now due on Wednesday, Nov 25 th  (No Quiz)  Go over the midterm  Backtrack and re-cover the question about tracing the.
Project 5: Using Pop-Up Windows Essentials for Design JavaScript Level One Michael Brooks.
Review of HTML and CSS A (very) brief review of some key fundamentals to be aware of in IT-238.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
Arrays and Loops. Learning Objectives By the end of this lecture, you should be able to: – Understand what a loop is – Appreciate the need for loops and.
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Tarik Booker CS 120 California State University, Los Angeles.
© 2010 Robert K. Moniot1 Chapter 6 Introduction to JavaScript.
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
Loops BIS1523 – Lecture 10.
Retrieving information from forms
Introduction to JavaScript
A second look at JavaScript
Introduction to JavaScript for Python Programmers
T. Jumana Abu Shmais – AOU - Riyadh
Training & Development
JavaScript objects, functions, and events
Introduction to JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
Web Programming and Design
Events Part I Mouse Events.
Events Part III The event object.
Modifying HTML attributes and CSS values
Random Stuff Colors Sizes CSS Shortcuts.
JavaScript Part 2 Organizing JavaScript Code into Functions
Retrieving information from forms
Presentation transcript:

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

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!

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

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');

Selecting ALL items: the each() function API for the each() function: 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.

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'); }

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.

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!

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!

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

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.

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!

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!! ');

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.