Writing to the Page Formatting Forms
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
getElementById
CHANGING HTML General structure: document.getElementById(“id-name”).attribute document.getElementById(“id”).innerHTML document.getElementById(“id”).className document.getElementById(“id”).src
Changing content
Writing to the page Use an id on any element Replace the element using innerHTML Keeps the correct tags (meaning) in HTML
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>’;
Changing classes
Changing class example document.getElementById(“id”).className =‘highlight’; And define that class in the CSS
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’;“
Changing images
Changing src example Change the picture with a button click onclick= “document.getElementById(“id”).src=‘cow.jpg’;”
Onclick Options
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
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
From alert to text Create an empty paragraph below the form Instead of an alert, add the text to the page
Changes more complex than a single assignment
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
But only interesting if content can change Content is random Content cones from user input Function needs to return a value return(value);
Random content Same onclick document.getElementById(‘newfield’).innerHTML = newcontent(); Function change: newcontent uses Math.random();
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;
Adding a function Change the onclick to call a function that you are to write.