Changing existing html elements: - University of Delaware



JavaScript: Tutorial 3 Included in this tutorial:document.getElementById()changing the width and height of an image (and src and alt)passing an id into a function and using it in document.getElementByIdreading info from a web page using document.getElementByIdchanging style using document.getElementByIdChanging existing html elements:So far to write out output, you’ve used:alert()document.write()Now, instead of creating new output or new html code, you’re going to learn to modify the html code that’s already in your document. For this you’ll use: document.getElementById()document.getElementById() accesses all the information about any element on your html page that has an id. It accesses the style, the size, the text, the src, etc. If it accesses it, that means you can change it. But this works specifically with elements THAT HAVE AN ID! That means that if you want to change something using document.getElementById, you must give that something an id first. Remember, every element is uniquely identified with an id. Thus the id is what allows the browser to know exactly which html element on your web page to access. Example: if you have an image on your web page, it might look like this in the html code:<img src = "pumpkin.png" style = "width: 512px; height: 512px;" alt = "a pumpkin">By adding an id to the image (e.g.,)<img src = "pumpkin.png" width=200 height=200 alt = "a pumpkin" id = "pump1">NOTE that I set width and height without saying: style = “…”. I did this to make using document.getElementById easier for this tutorial. This way of setting the width and the height is the old-fashioned way, but it works. Because we’re just using document.getElementById for the first time, setting and changing the width and the height are easier and more straight-forward when using the old-fashioned way of setting the width and the height.Using document.getElementById() you can modify:the src (change the image from pumpkin.png to some other image)the widththe height, and eventhe alt (if you changed the src to, say, “blackcat.gif”, you would want to change the alt as wellIn your javaScript, you’d have a line like this:document.getElementById('pump1').src = “blackcat.jpg”NOTICE that in between the parentheses is the id of the html element you are changing. Let’s try it:Step 1: to a web page (either a new one, or one you’ve already been working with) add an image. Step 2: give the image an id. Below is what mine looks like:<img src = "pumpkin.png" width=200 height=200 alt = "a pumpkin" id = "pump1">The id you added is what you will use to change the image. Step 3: Add a button (input type = “button”…) Make the value be “click to enlarge” and make the onClick call a function “enlarge(‘a’)”Note: right now you’re passing in the word ‘a’. There is no reason for this. It’s just a placeholder for now. Later, you’ll pass in something more relevant and use it in the function. For now, just pass in ‘a’ and trust me that it will eventually serve a purpose.Step 4: Save the html file. Load it and make sure the image shows up in your web page.Step 5. Now, in the .js file, add a function and call it enlarge(x).Step 6: In the file, add the following lines:function enlarge(x) {document.getElementById('pump1').width = 300document.getElementById('pump1').height = 300}Step 7: Save the .js file. Make sure the html file is linked to the .js file. Step 8: Load the .html file into a browser. Click on the button to enlarge. Your picture should get bigger. Step 9: Create another button in your html code. Make the value be “click to make smaller” and make it call a function shrink(‘b’) (again, sending in ‘b’ is useless for now)Step 10: In your .js code, create a second function called shrink(x). Inside the function, use document.getElementById to set the width to 100 and to set the height to 100. Step 11: Save the .js. Load the html into a browser and test both buttons. One should make the image larger, and the other should make the image smaller.Your Turn:Part 1: You’ve changed the .width and the .height of the image with an id. Now write a new function that changes the src and the alt tag. Create a button that calls this function. I changed my src from a pumpkin.jpg to a blackcat.jpg. I changed the alt to be “a black cat” You can change yours to anything you want. Notice how once you’ve changed the image src, you can still adjust the size of the new picture using the enlarge and make smaller buttons.Part 2: Instead of a separate button, you can add the onClick command directly inside the img html tag, e.g.,<img src=”bla.jpg” width = 300 height = 200 alt = “blab la bla” id = “mybla” onClick = “thefunc(‘mybla’)”>Add a new image to your web page. Give it an id. Download an alternate picture. I went with a clown pic and an explosion pic, but you can go with whatever you like. Now add another function to your .js code. The function should change the .src to the explosion pic. Now modify the image in your html code so that when you click on the image, the function you just wrote is called. Save all and test by loading into the browser. When you click on the image, it should change to your second pic.Using the parameter to send the id into the function:Right now the functions written only modify the image with the id of ‘pump1’. But you can have those two functions change the size of any image on your page by passing in the id of the image into the parameter, and then using the parameter in place of the id in document.getElementById(). Step 12: You’re going to modify the buttons on your html page as follows: Instead of passing in ‘a’ and ‘b’, send in the id of the image. In my example, the id is ‘pump1’ So if your image has the same id as mine, your button would be modified to look like this:<input type = "button" value = "click here to enlarge" onClick = "enlarge('pump1')">Step 13: Now, edit the .js file. You will be editing your enlarge(x) function. Do you see that x now holds ‘pump1’ when you click on the button? This means you can use x as if it is ‘pump1’. So your modified function would look like this:function enlarge(x) {document.getElementById(x).width = 300document.getElementById(x).height = 300}Notice that the x inside document.getElementById(x) does not have single quotes around it. This is because we don’t want the letter x, literally. There is no id of x in your html code. What you want is the value inside the parameter x. And when you click on the html button, the value ‘pump1’ goes into x, so now x holds ‘pump1’.If this doesn’t make sense, ask me about it. Step 14: Save the html and css. Load the html. Test the updated enlarge button. Your image should still grow in size.Step 15: Modify the shrink function so that you use the parameter in document.getElementById. Modify your html button that calls the shrink() function so that, instead of sending in ‘b’, you send in the id of the image ‘pump1’. Step 16: Save both the html and .js file. Test to make sure the updated shrink button works.Your Turn:Part a: Add 2 or 3 more images to your web page. Give each its own id.Now give each of the new images its own set of enlarge and shrink buttons. Each enlarge button should call the enlarge(x) function with the id associated with that image. Each shrink button should call the shrink(x) function with the id associated with that image.Note that you are not changing the .js file at all!!! Save yoru html. Test it by clicking on all the buttons. Each button should adjust the picture associated with it.Part b: Modify the function you created in the last Your Turn that changed the image’s src and alt to be a black cat (or the new image of your choice). Make the function have a parameter and use that parameter in document.getElementById. Add a button to each of the new images that calls the above function with the appropriate idSave the html and .js code. Test the modified function by click on each of the buttons associated with each of the images. Now when you click on these new buttons, the image should change from whatever it was to a black cat (or the image you chose).Part c: create a new function, askUser(x). For this function, instead of setting the width to a particular value (e.g., 300), use a prompt box to ask the user, “how wide do you want the image?” the user will type in a value, and that number should go into whatever variable you have to the left of the prompt. Use document.getElementById(x).width to set the width to the variable holding what the user typed in to the prompt box. For each of the images, create a button that calls the function askUser with the appropriate id inside the parentheses. Save the files, load them and test them to see if, when the user types something in, the width adjusts to what the user typed in.Using document.getElementById to get information:You have used document.getElementById to change existing information, but, like the prompt box, you can also use document.getElementById to obtain information about your html page. Let’s try it:Step 1: create a new function in your .js. Call it getInfo(x).Step 2: Inside the function, use a variable to hold what the width of an image is by using document.getElementById(x) as follows (the variable will be called y):y = document.getElementById(y).widthStep 3: to show what y holds, use an alert box as follows:alert(y)Putting this all together, you’d have:function getInfo(x) {y = document.getElementById(x).widthalert(y)}Step 4: Create a new (or modify an existing) html page. Add at least 2 images to the page, making sure each has a unique id. For each image, add a button that calls getInfo(x). Make sure each button in your html page, when it calls getInfo() has the id in single quotes in between the parentheses. Step 5: Save both files. Load the html page into a browser and test it by clicking on each of the buttons. When you click on the buttons, you should have an alert box that pops up Try: modify getInfo so that y holds the height instead of the width. Save and try. Then modify the function so that y holds the alt. Again, save and try. Modify one more time, so that y holds the src. Save and try. See how this works? Now put it back so that y holds the width.Since y holds the width, let’s use that information. You can add to and subtract from y, and then use the updated y value to modify the html image’s width. Step 6: Modify getInfo as follows::function getInfo(x) {y = document.getElementById(x).widthalert(y)z = y + 10alert(z)y = zalert(y)}Step 7: Save the .js and then run your html and test the functionCan you see how y updates to be the original width + 10? Let’s use that to update the width of your image.Step 8: Let’s get rid of everything but the last alert:function getInfo(x) {y = document.getElementById(x).widthz = y + 10y = zalert(y)}Step 9: Now let’s set the width to the updated y value:function getInfo(x) {y = document.getElementById(x).widthz = y + 10y = zalert(y)document.getElementById(x).width = y}Step 10: Save the .js. Load your html file and test the function by clicking on the button that calls getInfo(). You should see the width in an alert box, and then the width should increase by 10.Step 11: Click on the button multiple times. See how the width keeps increasing by 10 every time you click on it? This is because you are changing the width with document.getElementById(x).width = yOnce you do this, the width is now whatever number y holds. So the next time you call the function, and you do:y = document.getElementById(x).widthy will now hold the width that was updated last time you called the function. So you are adding 10 to the updated width. If you don’t understand this, ask me to explain more.Your Turn:Part 1: update getInfo. First, change its name to getLarger(x). Now, in addition to increasing the width by 10 every time you call the function, have the function increase the height as well. You will need different variables for this, so you may need to add something like this:q = document.getElementById(x).heightp = q + 10Your updated function should work such that every time you call getLarger, both the width and the height should increase by 10Part 2: Write a similar function getSmaller(x) that decreases the width and the height of an image by 10. Add buttons in the html that call this function. Now you should be able to click on both buttons and one will make the image get larger, and the other will make it get smaller for each image that calls getLarger and getSmallerPart 3: Add some conditions to your getLarger and getSmaller functions. The conditions should be as follows:If the height gets bigger than 300, you want to set it back to 100. Same with the width. So inside your function, after you’ve increased the value in y, and then later the q, you will use the y and the q in an if condition, for example:if (y > 300) {y = 100}You’ll do the same with q after you’ve increased the value in q.Part 4: do something similar to the getSmaller function such that if the width and the height get smaller than 20, reset them back to 100. Save and test.Using document.getElementById to change style:You can use document.getElementById to change the style of an html element. Again, whatever element you’re changing must have an id.Step 1 Add a paragraph to your html code. Give the paragraph an id (I gave it an id of ‘p1’). With the id, my paragraph looks like this:<p id = 'p1'> The time of year that Keats called the 'Season of mists and mellow fruitfulness', autumn is a season famous for its harvest time, turning leaves, cooling temperatures and darkening nights.</p>Step 2: in your .js file, create a new function. This function should take an input parameter. Let’s call this function changeStyle(par) (Notice that I changed the parameter’s name from x to par. I did this on purpose. The name of the parameter can be almost anything. So far we’ve used x, but we can use other names as well. So in this case, I named the input parameter par.)Step 3: inside the function, use document.getElementById to set the paragraph p1’s style such that the background color is brown, and the font color is pale yellow. We’ll give the paragraph an orange border, add some padding, and change the font to arial as follows:function changeStyle(par) {document.getElementById(par).style.backgroundColor= "#662200"document.getElementById(par).style.color= "#FFFFCC"document.getElementById(par).style.border= "6px solid orange"document.getElementById(par).style.padding= "15px"document.getElementById(par).style.fontFamily= "arial"}Step 4: Back in your html code, add a button that calls the changeStyle() function with the id of the paragraph.Step 5: Save the html, and the .js file. Load the html file into a browser and test it. Your paragraph’s style should change.Some things you can change with the style:backgroundColorbackgroundImagebackgroundPositionbackgroundRepeatborderColorborderStyleborderWidthmarginpaddingwidthposition colorfontFamilyfontSizefontWeightfontStylelineHeighttextAlignAnd more… Turn: Add at least 3 buttons, each with its own style. Make the value of the buttons for the style (so, for instance, if you have a button that changes the paragraph’s style to be Halloween themed, make the value of that button Halloween, etc.)Now, for each button add a corresponding function to your .js file. The function should take as an input parameter an id. The function should adjust the html element’s style to correspond to the theme of the function (so, for instance, going with my Halloween theme, I might add a backgroundImage of bats, I might make the font orange and the background black, etc. innerHTML:So far we’ve changed the style of something with an id, the src, the width, the height, and the alt of an image, but we haven’t changed the actual content of your html page. For Changing the content can be done using innerHTMLFirst, you must understand exactly what innerHTML is. The innerHTML is what is between the opening and the closing tag, regardless of what the tag is. So in the following html code:<p id = “firstp”> This is the innerHTML text between the opening and closing tag</p>The innerHTML of firstp is: “This is the innerHTML text between the opening and closing tag”In this html code:<h1 id = “largeheader”>Autumn</h1>The innerHTML of largeheader is “Autumn”In this html code:<a href = "" id = "coolcows">link to cows are awesome</a>The innerHTML is “link to cows are awesome”Let’s start with this:CoStep 1: in your html page, add 3 paragraphs. Give each an id. Make each call the function, readinnerHTML (that you will be writing shortly) with its id as a parameter. For now, make the content of the paragraph short – a one-word thing, like a season, an animal, a holiday, something like that. So, for instance, one of the 3 paragraphs might looks like this:<p id = 'p1' onClick = "readinnerHTML('p1')"> Cows </p>Step 2: Save your html page. Load it in a browser just to be sure it’s working.Step 3: in your .js file, add a function readinnerHTML(par). The function will read the innerHTML of whatever id you sent into the function. And then you’ll use an alert to print it out (for now). So the function will look like this:function readinnerHTML(par) {x = document.getElementById(par).innerHTMLalert("you clicked on " + x)}Step 4: Save the .js file and test the function by clicking on each of the paragraphs.Do you understand what happened? When you clicked on the paragraph, you sent the id of the paragraph into the parameter par in the function in the .js file. Then document.getElementById(par).innerHTML gets the innerHTML, or whatever is between the opening and closing tag of the element with the id. That is put into the variable x. So x holds the stuff between the opening and closing tag. The alert box is then used to print out, ‘you clicked on ‘ and whatever x holds. So the alert box is printing out the innerHTML of each of the paragraphs when you click on them.You can make this more interesting by adding an ‘if’ condition to your function. The if condition will add more information about whatever the user clicked on. To give you an example, I had as my paragraphs, a cow, a giraffe, and a panda. So my if condition looks like this:if (x === 'Cows') {y = "You are more likely to be killed by a cow than a shark"}else if (x === 'Giraffes') {y = "A giraffe's legs are longer than most humans are tall, and their necks are too short to reach the ground"}else if (x === 'Pandas') {y = "A baby panda eats its mother's poop, and all pandas have 6 digits on their paws"}So the variable y will hold extra information about the paragraph the user clicked on.And finally, you will want to put the innerHTML together with the new information. I included a “: “ between the two so they’re nicely separated:alert(x + ": "+y)So the modified function will look like this:function readinnerHTML(par) {x = document.getElementById(par).innerHTMLif (x === 'Cows') {y = "You are more likely to be killed by a cow than a shark"}else if (x === 'Giraffes') {y = "A giraffe's legs are longer than most humans are tall, and their necks are too short to reach the ground"}else if (x === 'Pandas') {y = "A baby panda eats its mother's poop, and all pandas have 6 digits on their paws"}alert(x + ": "+y)}Step 5: Modify your function to resemble the function above, only with y holding information appropriate to the paragraphs on your html page.Step 6: save both the html and the .js, and load the .html into a browser and test it.Instead of using an alert box, you can also replace the existing paragraph with the new, expanded information. To do that, you’d replace the js code, alert(x + “: “ + y) withdocument.getElementById(par).innerHTML = x + ": "+yStep 6: Modify your function above by replacing the alert box with the above document.getElementById. Save both the html and the .js code, and test this in the browser. Make sure you understand what is going on!! Make sure you understand what x holds, and also that par holds the id of an element on your html page. The element whose innerHTML is being read and the element whose innerHTML is being changed are both identified by the id in the par parameter.You can use document.getElementById to modify another paragraph on your web page.Step 7: Add both an image and another paragraph above the 3 paragraphs you created in step 1, above. Give the paragraph an id of ‘mainid’.Step 8: modify the bottom document.getElementById() that changes the innerHTML (not the one that reads the innerHTML). You are going to change it so that, instead of modifying the paragraph that calls the function, you modify the mainid paragraph simply by changing the innerHTML of that bottom document.getElementById(). So that bottom line will now look like this:document.getElementById('mainid').innerHTML = x + ": "+yStep 10: Save your html code and your .js file. Load the html code and click on each of the paragraphs (not the mainid paragraph). When you click on a paragraph, the mainid paragraph should change text to reflect the paragraph you clicked on.Your Turn:In step 7, you added an image to the html code. Give the image an id. You can now use document.getElementById() with the id of the image to change the .src of the image, along with the mainid’s paragraph. Modify the function you created above so that, depending on what paragraph is clicked on, an appropriate image shows up as well as a longer paragraph. Modify the style of the paragraph so that it fits with either the image’s colors or the paragraph’s themes (so, for instance, if you’ve got the word Panda as a paragraph, when you click on it, you want a picture of the panda to pop up in the image’s spot, text about pandas to pop up in the mainid paragraph, and maybe give the mainid paragraph a background of bamboo with a yellow-green border and yellow text, or something like that). Note that to do this, you’ll have to modify each of the if conditions so that each one uses document.getElementById to change the image’s src and also to change mainid’s style. ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download