Skip to content Skip to sidebar Skip to footer

Javascript Function That Changes Text Color, Hyperlink Color, And Image

Hi, I need help with a class assignment. We were given an HTML file for a pretend business, 'Castaway Vacations LLC'. The first step in the assignment is to create a javascript f

Solution 1:

ok, for starters to change color of something you just need to do something like this

functionchange_color(){ 
 document.body.style.color = "red";  // this will change the color of the text to REDdocument.getElementById("image_to_change").src = "something.jpg"; // change img src
}

to use the function just add the call to the function where you want it, for example

<aonClick="change_color();"href="#">Romantic</a><br><br>

well, its already accepted answer, but just wanted to complete it, to change the img src of, first you need to add an id for that img, for example

<tdalign="center"><imgid="image_to_change"src="orig_main.jpg"><br><i>Your Vacation Awaits!

after you added the id, you can see how i added this line to the "change_color" function

document.getElementById("image_to_change").src = "***SOURCE_TO_YOUR_IMAGE***";

* Working Code * OK, here is the working fiddle http://jsfiddle.net/8ntdbek3/1/ i changed a few things to make it work, first, you need to understand that when you give an "ID" to something, in this case to the img (you gave the id "rom_main.jpg") the ID is what you need to use to call that element, so when you are using

document.getElementById("orig_main.jpg").src = "rom_main.jpg";

it should go

document.getElementById("rom_main.jpg").src = "rom_main.jpg";

since you gave it the id "rom_main.jpg" in this line, and the id "orig_main.jpg" does not exist!

<tdalign="center"><imgid=**"rom_main.jpg**" src="orig_main.jpg"><br><i>Your Vacation Awaits!

also its important to note that you can put ANY id that you want, so repeating the name of the jpg file its something that i would not recommend, since it leads to confusion.

I changed the ID to something more readable and thats it. if you still need help comment below and i'll do my best to help you.

* EDIT to change color *

ok, finally i added a few lines of code to change the color of EVERY element in your page, for each onclick i adde these lines:

var list = document.getElementsByTagName("a");     
for (i = 0; i < list.length; i++) { 
  list[i].style.color = "red";  
}

as you can see, i get in a list every element with the tag "a", then every element i turn it into "red" (or the color you want).

here is the working fiddle http://jsfiddle.net/8ntdbek3/3/

regards.

Post a Comment for "Javascript Function That Changes Text Color, Hyperlink Color, And Image"