JS Tutorial 3: InnerHTML Note: this part is in last week s tutorial as well, but will be included in this week s lab

Similar documents
link document.getelementbyid("coffee").style.borderwidth = "0px" document.getelementbyid("tea").style.borderwidth = "10px"

Programming Lab 1 (JS Hwk 3) Due Thursday, April 28

JS Lab 1: (Due Thurs, April 27)

LECTURE-3. Exceptions JS Events. CS3101: Programming Languages: Javascript Ramana Isukapalli

JavaScript: Tutorial 5

Loops/Confirm Tutorial:

Want to add cool effects like rollovers and pop-up windows?

javascript Tutorial 4

The first sample. What is JavaScript?

Events: another simple example

Web Programming and Design. MPT Junior Cycle Tutor: Tamara Demonstrators: Aaron, Marion, Hugh

Fundamentals of Website Development

<script> function yourfirstfunc() { alert("hello World!") } </script>

The default style for an unordered (bulleted) list is the bullet, or dot. You can change the style to either a square or a circle as follows:

Introduction to JavaScript

Arrays/Branching Statements Tutorial:

HTML User Interface Controls. Interactive HTML user interfaces. Document Object Model (DOM)

HTML Tags (Tutorial, Part 2):

Introduction to using HTML to design webpages

LECTURE-2. Functions review HTML Forms. Arrays Exceptions Events. CS3101: Scripting Languages: Javascript Ramana Isukapalli

HTML. Mohammed Alhessi M.Sc. Geomatics Engineering. Internet GIS Technologies كلية اآلداب - قسم الجغرافيا نظم المعلومات الجغرافية

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

CS1046 Lab 4. Timing: This lab should take you 85 to 130 minutes. Objectives: By the end of this lab you should be able to:

JavaScript is described in detail in many books on the subject, and there is excellent tutorial material at

Web Development & Design Foundations with HTML5

Programmazione Web a.a. 2017/2018 HTML5

New Perspectives on Creating Web Pages with HTML. Tutorial Objectives

a.) All main headings should be italicized. h1 {font-style: italic;} Use an ordinary selector. HTML will need no alteration.

How the Internet Works

HTML, CSS, JavaScript

Introduction to DHTML

Controlled Assessment Task. Question 1 - Describe how this HTML code produces the form displayed in the browser.

Name Related Elements Type Default Depr. DTD Comment

JAVASCRIPT BASICS. Handling Events In JavaScript. In programing, event-driven programming could be a programming

Web Design and Application Development

JSF - H:INPUTSECRET. Class name of a validator that s created and attached to a component

JavaScript Handling Events Page 1

EVENT-DRIVEN PROGRAMMING

Exercise 1 Using Boolean variables, incorporating JavaScript code into your HTML webpage and using the document object

Client vs Server Scripting

Mouse-over Effects. Text based buttons

Microsoft Expression Web Quickstart Guide

A Balanced Introduction to Computer Science, 3/E

ORB Education Quality Teaching Resources

Place User-Defined Functions in the HEAD Section

JavaScript Introduction

Interactive Tourist Map

CS Multimedia and Communications REMEMBER TO BRING YOUR MEMORY STICK TO EVERY LAB!

A340 Laboratory Session #5

CSC Javascript

By the end of this section of the practical, the students should be able to:

JavaScript and XHTML. Prof. D. Krupesha, PESIT, Bangalore

AOS Lab 4 HTML, CSS and Your Webpage

Introduction to JavaScript, Part 2

11. HTML5 and Future Web Application

Javascript. A key was pressed OR released. A key was released. A mouse button was pressed.

introduction to XHTML

CSE 154: Web Programming Autumn 2018

8/19/2018. Web Development & Design Foundations with HTML5. Learning Objectives (1 of 2) Learning Objectives (2 of 2) What is JavaScript?

INTRODUCTION TO WEB USING HTML What is HTML?

Lesson 5: Introduction to Events

COMP 101 Spring 2017 Final Exam Section 1 Friday, May 5

Lab 5: Dreamweaver CS5, Uploading your Web site

Beijing , China. Keywords: Web system, XSS vulnerability, Filtering mechanisms, Vulnerability scanning.

NEW WEBMASTER HTML & CSS FOR BEGINNERS COURSE SYNOPSIS

PIC 40A. Midterm 1 Review

HTML5: Adding Style. Styling Differences. HTML5: Adding Style Nancy Gill

New Media Production Lecture 7 Javascript

What is Java Script? Writing to The HTML Document. What Can JavaScript do? CMPT 165: Java Script

CSS Tutorial Part 1: Introduction: A. Adding Style to a Web Page (3 options):

Web Engineering (Lecture 06) JavaScript part 2

INLEDANDE WEBBPROGRAMMERING MED JAVASCRIPT INTRODUCTION TO WEB PROGRAMING USING JAVASCRIPT

HTML Summary. All of the following are containers. Structure. Italics Bold. Line Break. Horizontal Rule. Non-break (hard) space.

**Method 3** By attaching a style sheet to your web page, and then placing all your styles in that new style sheet.

Enlargeit! Version 1.1 Operation Manual

CMPT 100 : INTRODUCTION TO

<form>. input elements. </form>

Canvas & Brush Reference. Source: stock.xchng, Maarten Uilenbroek

Using Dreamweaver CS6

CISH-6510 Web Application Design and Development. Overview of JavaScript. Overview

HTML and CSS: An Introduction

Creating Web Pages Using HTML

Using Dreamweaver CS6

Web Programming and Design. MPT Senior Cycle Tutor: Tamara Week 1

CSS worksheet. JMC 105 Drake University

TEXTAREA NN 2 IE 3 DOM 1

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Dreamweaver Basics Workshop

CoderDojo Activity Cards: The Cards (Animation2.html): How to use: Student comes to mentor, and together they choose a card to do next.

Perfect Student Midterm Exam March 20, 2007 Student ID: 9999 Exam: 7434 CS-081/Vickery Page 1 of 5

Random number generation, Math object and methods, HTML elements in motion, setinterval and clearinterval

Key features. Nothing to do with java It is the Client-side scripting language Designed to add interactivity to HTML pages

Exercise 1: Understand the CSS box model

var num1 = prompt("enter a number between 1 and 12","1"); var promptstring = "What is " + num1 + " times 3?"; var num2 = prompt(promptstring);

Using Dreamweaver CC. 6 Styles in Websites. Exercise 1 Linked Styles vs Embedded Styles

MPT Web Design. Week 1: Introduction to HTML and Web Design

1$ 5 ! $ 6 4 * Source: 0 "!*! 0! * 8 97 ?!$ 5 0 *! 4! $ 0 : * ' () 7;7 7<7

Lesson 1: Writing Your First JavaScript

More cool scripts: Slide Show: What the settimeout() function does:

710 Index Attributes, 127 action attribute, 263 assigning, bottom attribute, domain name attribute, 481 expiration date attribute, 480 8

Transcription:

JS Tutorial 3: InnerHTML Note: this part is in last week s tutorial as well, but will be included in this week s lab What if we want to change the text of a paragraph or header on a page? You can use: document.getelementbyid().innerhtml For example, in the following code, if you want to change the text between the opening and closing <p> tags for the paragraph with the id, firstp, you could do the following: <p id = "firstp"> This is a paragraph</p> <p id = "secondp">this is a second paragraph</p> var x = prompt("do you want to see new text?") if (x == yes ) document.getelementbyid("firstp").innerhtml = "Some new text"; </body> The innerhtml is what is between the opening and the closing tag, regardless of what the tag is: <p id = firstp > This is the innerhtml text between the opening and closing tag</p> Above, the innerhtml is: This is the innerhtml text between the opening and closing tag To change it: document.getelementbyid( firstp ).innerhtml = new text for paragraph <h1 id = firsth >Title goes here </h1> Above: innerhtml is: Title goes here To change it: document.getelementbyid( firsth ).innerhtml = New Title Try: In the following example: <p id = linked > <a href = udel.edu id = firstlink > link to udel </a></p> What is the innerhtml of linked? What is the innerhtml of firstlink? How would you change the innerhtml of linked to a new link? <ol id = list1 > <li id = firstitem > cats </li> <li id= seconditem > dogs </li> </ol>

What is the innerhtml of list1? What is the innerhtml of firstitem? How would you change the innerhtml of list1 to a new list? Confirm box The confirm box is like the prompt box, only in this case you only have the choice of choosing ok or cancel. To create a confirm box, you d write the following code: var x = confirm( Press a button! ) A confirm box will pop up that looks like this: If you choose ok, the x variable will hold true. If you choose cancel, the x variable will hold false. Aside: true and false are known as Boolean values Here is an example of using the confirm box: <p id = p1 > hi there </p> var x=confirm("press a button") if (x==true) document.getelementbyid( p1 ).innerhtml="you pressed OK!" else document.getelementbyid( p1 ).innerhtml ="You pressed Cancel! Now, given all you know, can you follow the following script? <h1>learn about <span id = "animal">animals</span></h1> <p><img width = "230" height = "200" id = "pic1" alt = "animal pic"> </p> <p id = "firstp"> You can learn so much about every animal in the zoo!</p> var animals = new Array() animals[0] = "lions" animals[1] = "giraffes" animals[2] = "penguins" animals[3] = "polar bears" var pics = new Array() pics[0] = "Images/lion.jpg" pics[1] = "Images/giraffe.jpg" pics[2] = "Images/penguin.jpg" pics[3] = "Images/polarbear.jpg"

var info = new Array() info[0] = "Lions are the second largest big cat species in the world (behind tigers). The roar of a lion can be heard from 8 kilometers (5.0 miles) away." info[1] = "A male giraffe can weigh as much as a pick up truck! Although a giraffe s neck is 1.5 1.8 metres, it contains the same number of vertebrae at a human neck." info[2] = "Penguins spend around half their time in water and the other half on land. Penguins spend around half their time in water and the other half on land." info[3] = "Polar bears keep warm thanks to nearly 10 cm of blubber under the skin. Polar bears have black fur under their outer layer of white fur." var x = confirm("would you like to learn about an animal?") if (x == true) var num = Math.floor(Math.random()*4) document.getelementbyid("animal").innerhtml = animals[num]; document.getelementbyid("pic1").src = pics[num]; document.getelementbyid("firstp").innerhtml = info[num]; </body> Functions So far in our code we ve had javascripts that load and run when the web page loads in the browser. In order to make the javascript run again, we have to reload the page in the browser. So, for example, last week we saw a web page with a script that used a prompt to ask the user, Would you like to learn about an animal? and if the user answered yes, the script generated a random number and then used that random number to change the header to the name of the animal, the image to a picture of the animal, and the paragraph to a paragraph about the animal. If the user wanted to learn about a different animal, the user had to reload the entire web page. In another example, a script used a prompt to ask the user, Heads or Tails? and then, depending on what the user chose and the random number generated the script either wrote a paragraph, Congratulations! You guessed correctly! or Sorry, you guessed heads and the computer generated tails. (or vice versa). Again, if the user wanted to play again, the user had to reload the web page in the browser. Wouldn t you prefer to create a web page with a button, and every time you clicked the button, the script happened again? Then if you wanted to run the javascript again, you would just need to click on the button. You can do this by adding a function and a button. A function is, essentially, naming your javascript code. When you give your javascript code a name, you can call it, or make it run, by calling the name of the function. Every time you call the name of the function, the browser will run it, without having to reload the web page. Defining a function function fname () javascript code that function does

Above is a basic template for a function. You must first declare that you are creating a function, so the very first word in the creation of a function is, well, function. Fname is any name you choose to give your function. You can choose any name you wish, as long as it follows the javascript naming conventions (i.e., no spaces, no special characters other than _, must start with a letter, and can t be a reserved javascript word. After the name of the function, you must have the (and ). Later we may put something between those parentheses, but for now we can just include () after the function s name. Then all the code that you want to belong to your function must go between an opening and closing Example: <!DOCTYPE html><html><head> <meta charset= "utf-8" ></head> <p id = "firstp"> This is a paragraph</p> function guessinggame() var x = Math.floor(Math.random()*6) + 1 var y = parseint(prompt("enter a number between 1 and 6")) if (x == y) document.getelementbyid("firstp").innerhtml = "You guessed it!"; else document.getelementbyid("firstp").innerhtml = "You are wrong!"; Above is an example of including a function in your javascript code. The function includes all code between its opening and its closing. We turned code into a function for a reason. By making javascript code into a function and giving it a name, we can make the code happen whenever we call its name (e.g., by clicking a button on our web page, which we will learn how to add next). That means that the code inside of a function doesn t happen automatically. I m going to repeat that. The code inside a javascript function doesn t happen whenever you load the web page. So in order to make the code inside the function, we must call its name somehow. One way to do that is to add a button to our web page and make that button call the function s name. Adding a button The button is technically not javascript code it is HTML code. So it must go in the web page, but not inside your script. The button does, however, call the javascript function s name, and, in doing so, makes the function happen. To include a button in your web page, you d include the following html code: <input type = "button" value = "Click to play" onclick = "guessinggame()"> Breaking it down, this html code will create a button, with the text, Click to play on it. When you click it, it calls the function you named guessinggame(), thus making the code inside the function be executed by the browser.

So, putting it all together, you d get: <!DOCTYPE html><html><head> <meta charset= "utf-8" ></head> <p id = "firstp"> This is a paragraph</p> <input type = "button" value = "Click to play" onclick = "guessinggame()"> function guessinggame() var x = Math.floor(Math.random()*6) + 1 var y = parseint(prompt("enter a number between 1 and 6")) if (x == y) document.getelementbyid("firstp").innerhtml = "Play the lottery!"; else document.getelementbyid("firstp").innerhtml = You are wrong!"; So, in the above example, the function guessinggame does not happen automatically. It is only executed when we click on the button. But we can click on the button again and again. Each time we click on it, the code inside the function will run. This is more efficient than reloading the entire web page in the browser. Placing functions in the head section: So far we ve placed all of our javascript code in the body of the web page. javascript code, and in particular functions, can go in the body section of our html code or in the head section of the html code. With functions, we usually put them in the head section. The reason is that if there are images involved, by putting it in the head section, the images will preload. If we put the code in the body section, the images won t download until the function is called, making it run slow. Plus, when we put the functions inside the body of our html code, it s just sloppier and harder to read through the html page. By separating the javascript and placing it in the head section, the web page is cleaner to read through. We can also place javascripts into separate files and link the separate file in the head section, like we did with the css style sheet. But for now, let s just place the javascript code in the head section. Below is an example of placing the javascript code in the head section of your html page: <!DOCTYPE html><html> <head> <meta charset= "utf-8" > function show_confirm() var r=confirm("press a button"); if (r==true) document.getelementbyid('p1').innerhtml = "You pressed OK!"; else document.getelementbyid('p1').innerhtml = "You pressed Cancel!"; </head>

<input type="button" value="show confirm box" onclick="show_confirm()" > <p id = "p1"> Answer goes here </p> </body> </html> In the following example, there are two functions in the head section, each with its own name. Every function name within a javascript has to be unique. <!DOCTYPE html><html><head><meta charset= "utf-8" > function coffeeinfo() document.getelementbyid('p3').innerhtml = "<p>the word 'coffee' was at. </p>" document.getelementbyid('p3').style.color = "#CCBBAA" document.getelementbyid('p3').style.backgroundcolor = "#995500 </p>" function teainfo() document.getelementbyid('p3').innerhtml = "<p>the origin of tea can be traced.. document.getelementbyid('p3').style.color = "#227700" document.getelementbyid('p3').style.backgroundcolor = "#BBCC22 document.getelementbyid("p3").style.bordercolor = "#114400" document.getelementbyid("tea").style.bordercolor = "#114400 document.getelementbyid("tea").style.borderwidth = "10px" document.getelementbyid("coffee").style.borderwidth = "0px" </head> <table ><tr><td > <img src = "Images/coffee.jpg" width = "300" height = "280" alt = "pic of coffee" id = "coffee"> </td><td> <img src = "Images/tea.jpg" width = "360" height = "280" alt = "pic of tea" id = "tea"> </td></tr> <tr><td> <input type = "button" value = "Learn more about coffee" onclick = "coffeeinfo()"> </td><td> <input type = "button" value = "Learn more about tea" onclick = "teainfo()"> </td></tr> <tr><td colspan = "2" id = "p3"> </td></tr> </table> Methods for calling Functions (making them be executed by the browser) There are a number of ways you can make a function happen in JavaScript. You ve seen onclick= functionname() There s also:

onmouseover() when you run your mouse over something onmouseout() when you take your mouse pointer off of something onload() for when the web page loads I use the above frequently, along with onkeypress(below). But there are a number of other options we can include in the html code for calling javascript functions, including: ondblclick() when you double-click on something onfocus() when you put your cursor into a form element like a textbox onblur() when your cursor leaves a form element onkeydown () when you press a key down over something onkeyup() when you release a key over something onkeypress()- when you press and release a key over something onmousedown()- when you click the mouse over something (but don t release it) onmouseup() when you release the mouse over something onmousemove()- moving the mouse while hovering over something onsubmit() when submitting a form onunload() when you leave the current web page window you re in. OnMouseOver and onmouseout: Below is an example of using onmouseover and onmouseout to call the javascript functions. In the example, there are two javascript functions, changepara() and changethanks(). In the html code in the body of the web page is a button. Moving your mouse over the button (you don t need to click on it just run your mouse over it) will call the function, changepara() and the code inside it will be executed. When you move your mouse off of the button, the function changethanks() will be called and executed. <!DOCTYPE html><html> <head> <meta charset= "utf-8" > function changepara() document.getelementbyid('firstp').innerhtml = "GET YOUR MOUSE OFF THAT BUTTON!" function changethanks() document.getelementbyid('firstp').innerhtml = "Whew, that was close!" </head> <p id = "firstp">this is a very important paragraph!!!</p> <input type = "button" value = "Don't click here" onmouseover = "changepara()" onmouseout = "changethanks()"> onmouseover and onmouseout (and onclick, and almost every other method for calling functions) will work on any element with a tag on your web page. You don t have to create a button you can place onmouseover and onmouseout in a paragraph, for example. In the code below, there s a paragraph with the id, firstp. Inside the paragraph tag, there s a call to changepara() that happens in an onmouseover event (i.e., when you run your mouse over the paragraph with the id firstp ). Now, when you run your mouse over the paragraph, the function

changepara() is called and executed. The function changepara() changes the innerhtml of the element with the id firstp to DON T RUN YOUR MOUSE OVER THIS PARAGRAPH!. That means when you move your mouse over the paragraph, firstp, its text changes. Equally, when you move your mouse off the paragraph, the function changethanks() will be called and the code will be executed, meaning the innerhtml of the element with the id firstp (the paragraph) will be changed to, Thanks for taking your mouse off this paragraph. So to summarize, when you move your mouse over the paragraph firstp, the text changes to, DON T RUN YOUR MOUSE OVER THIS PARAGRAPH! and when you mover your mouse off of the paragraph, the text will change to, Thank you for taking your mouse off this paragraph. <!DOCTYPE html><html><head> <meta charset= "utf-8" > function changepara() document.getelementbyid('firstp').innerhtml = "DON'T RUN YOUR MOUSE OVER THIS PARAGRAPH!" function changethanks() document.getelementbyid('firstp').innerhtml = "Thank you for taking your mouse off this paragraph" </head> <p id = "firstp" onmouseover = "changepara()" onmouseout = "changethanks()"> This is a very important paragraph!!!</p> Equally, you can call functions using onmouseover and onmouseout on images on your web page. The functions called can change the images to new images. See if you can figure out what the following code does: <!DOCTYPE html><html><head> <meta charset= "utf-8" > function changepic() document.getelementbyid('pic1').src = "ghost.jpg" function changeback() document.getelementbyid('pic1').src = "woman.jpg" </head> <p><img src = "woman.jpg" width = "300" height = "300" id = "pic1" onmouseover = "changepic()" onmouseout = "changeback()"> </p> In the above example, when you move your mouse over the image on the web page with the id, pic1, the src of the image (the picture) changes from woman.jpg to ghost.jpg. When you move your mouse off of the image, the src picture changes back to that of a woman.

Comments Comments are a way of including comments to yourself and to other people. Comments are not executed by the browser (the browser completely ignores them! The ONLY time they show up is when you load your web page into textwrangler or notepad++. They never show up in the browser s display. Comments start with /* and end with */. Everything between these opening and closing markers is ignored by the browser,so anything between them won t be run by javascript. For example: /* This script asks the user for a number. It uses that number to set the element with the id ball1 to the width of the number the user entered */ var x = parseint(prompt("what size should the ball's width be?")) document.getelementbyid("ball1").width = x Comments are designed for leaving information for people to read (as opposed to the browser). However, we can use comments to isolate what code is working and what isn t Debugging: When your code doesn t work, we say, there is a bug in your code. Finding the bug and fixing it, so your code works, is known as debugging. There are 2 types of errors in code: 1. It could be a "syntax error" These include typos, which happen a lot. Syntax errors include capitalizing a letter that should be small, e.g., var num = 3 Num = 4 e.g., document.getelementbbyid('pic1).src = "cat.jpg"; e.g., forgetting an opening or closing or ( ) e.g., if (par1 = 'pic1') 2. Could be a logic error These are the hardest to find! When what you're trying to do won't be done in the way you're trying to do it. How do you go about finding the bug? It can be tricky and frustrating. But there is a systematic way to narrow down exactly where the problem is. Finding the bug (Debugging) 1. Is your web site showing up as you want it to? Probably an html error

1. Make sure the page is valid (you ve got an opening and closing <html> tag and an opening and closing tag inside it. 2. Check to make sure that if you opened a tag, you closed it properly. 2. Is the javascript just not working at all? Check to make sure everything opened is closed 1. Make sure your quotes (" ") open and close properly 1. Make sure the quotes are " " and not (from copying from ppt or word) 2. Go through and check for opening and closing () and 3. CHECK CAREFULLY FOR PROPER CAPITALIZATION 4. If nothing shows up, check to make sure you've properly entered, (I ve seen a lot of <scirpt> tags ) If none of that works, you can always try isolating the bug by putting comments around parts of your code to see where the code is working and where it isn t. For instance, if the script isn t working at all, put comments around a section. If the part that s remaining works, it means that the problem is inside the part that you commented out.