Download presentation
Presentation is loading. Please wait.
1
Writing to the Page Formatting Forms
2
Lab starting point (review)
Create an HTML page that has a form on it with 2 input fields for a first name and a last name, each with a label Button that when clicked creates an alert that says Hi first-name
3
getElementById
4
CHANGING HTML General structure: document.getElementById(“id-name”).attribute document.getElementById(“id”).innerHTML document.getElementById(“id”).className document.getElementById(“id”).src
5
Changing content
6
Writing to the page Use an id on any element Replace the element using innerHTML Keeps the correct tags (meaning) in HTML
7
What to Write Generate HTML that you want.
Concatenate literals and variables. Example: Build a paragraph using a variable called “content” document.getElementById(“id”).innerHTML = ‘<p>’+content+’</p>’;
8
Changing classes
9
Changing class example
document.getElementById(“id”).className =‘highlight’; And define that class in the CSS
10
Mouseover example Highlighting when mouseover
Requires that you change it back when you mouseout onmouseover= “document.getElementById(“id”).className=‘highlight’;” onmouseout= “document.getElementById(“id”).className=‘normal’;“
11
Changing images
12
Changing src example Change the picture with a button click
onclick= “document.getElementById(“id”).src=‘cow.jpg’;”
13
Onclick Options
14
Simple Change Onclick makes the change in a simple assignment statement document.getElementById(‘newfield’).innerHTML = ‘This is new content!’; Requirement: newfield is an id on the page whose content can be changed Very often there is no information there yet
15
Or Use User Input Onclick still makes the change in a simple assignment statement What is assigned changes: document.getElementById(‘newfield’).innerHTML = ‘Hi ’+document.getElementById(‘yourname’).value; Same requirements on newfield
16
From alert to text Create an empty paragraph below the form
Instead of an alert, add the text to the page
17
Changes more complex than a single assignment
18
Use a function instead of a literal
Onclick STILL makes the change in a simple assignment statement document.getElementById(‘newfield’).innerHTML = newcontent(); Same requirements on newfield
19
But only interesting if content can change
Content is random Content cones from user input Function needs to return a value return(value);
20
Random content Same onclick
document.getElementById(‘newfield’).innerHTML = newcontent(); Function change: newcontent uses Math.random();
21
User Input Now onclick passes a parameter
document.getElementById(‘newfield’).innerHTML = newcontent(document.getElementById(‘you’).value); Function change: newcontent now takes a parameter and uses it;
22
Adding a function Change the onclick to call a function that you are to write.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.