MrBool
You must be logged in to give feedback. Click here to login
[Close]

You must be logged to download.

Click here to login

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

[Close]

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to modify the properties and content of a web page using JavaScript

In this article we will focus on using JavaScript in conjunction with a select element to change the properties of a web page, to show and hide elements in a web page and to modify the content of an element.

[close]

You didn't like the quality of this content?

Would you like to comment what you didn't like?

JavaScript is the most popular client-side scripting language and it works in the all major browser like Internet Explorer, Firefox, Chrome, Opera and Safari. JavaScript was designed to add interactivity to the web pages, it’s a simplified programming language and it’s an interpreted language that means that the browser executes the JavaScript code without pre-compiling it.

JavaScript can dynamically insert text in HTML page, can react at events like click on a button or change the selected option in a element, can read and modify the content of a HTML element, can validate the user’s input in forms and it can create cookies.

In the first example we will use two <select> element, one to select the color of the web page background and second to change the font family of the document. We will use onChange() event for each <select> element to change the background color and/or the font family for our page. This event occurs every time the user chooses a new option from the <select> element. To retrieve the chosen option we will use the property options which return an array containing all the options declared in that <select> element and the property selectedIndex which return the index of the option currently selected (indexed from 0).

Listing 1: Code for the web page

<!Doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>First Example</title>
	</head>
	<body>
		<h1>Changing the background color and font family using JavaScript</h1>
		<p>
			Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
			incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
			exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
                                           irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
                                           pariatur. 
			Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
                                            mollit anim id est laborum.
		</p>
		<p id="second">
			Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
                                           doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
                                           veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim
                                           ipsam voluptatem quia voluptas sit aspernatur aut 	odit aut fugit, sed quia
                                           consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. 
			Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, 
                                           adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et
                                           dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis
                                           nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea
                                           commode consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate 
                                           velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo
                                           voluptas  nulla pariatur?
		</p>
		
		<form>
			<label>Select the background color</label>
			<select id="colorSelection">
				<option value="none"></option>
				<option value="red">Red</option>
				<option value="green">Green</option>
				<option value="blue">Blue</option>
			</select>
			   
			<label>Select the font family</label>
			<select id="fontSelection">
				<option value="none"></option>
				<option value="verdana">Verdana</option>
				<option value="courier">Courier New</option>
				<option value="arial">Arial</option>
			</select>
		</form>
		
		<script>
			//retrieve from document first <select> element
			var colorSelection=document.getElementById("colorSelection");
			//retrieve from document second <select> element
			var fontSelection=document.getElementById("fontSelection");
			
			//use onChange event for first <select> element
			colorSelection.onchange=function() {
				//retrieve the chosen option from first <select> element
				var chosenColor=this.options[this.selectedIndex];
				//change background color
				switch (chosenColor.value) {
					case "red":
						document.bgColor="#ed1f24";
						break;
					case "green":
						document.bgColor="#3ab449";
						break;
					case "blue":
						document.bgColor="#29aae1";
						break;
					default:
						document.bgcolor="#ffffff";
				}
			}
			
			//using onChange event for second <select> element
			fontSelection.onchange=function() {
				//retrieve the chosen option from second <select> element
				var chosenFont=this.options[this.selectedIndex];
				//change font family
				switch (chosenFont.value) {
					case "verdana":
						document.body.style.fontFamily="Verdana,sans-serif";
						break;
					case "courier":
						document.body.style.fontFamily="Courier,monospace";
						break;
					case "arial":
						document.body.style.fontFamily="Arial,sans-serif";
						break;
					default:
						document.body.style.fontFamily="Times,serif";
				}
			}
			
		</script>
	</body>
</html>

As you can see, the code is written using the new HTML 5 tags. The image bellow shows a screenshot of the web page with background color and font changed:

Screenshot of the web page with background color and font changed

Figure 1: Screenshot of the web page with background color and font changed

In the second example we will use JavaScript to hide and display two <div> elements on the web page. Let’s assume that your website has a page for selling an e-book and the user has two options: he can choose to send you a message asking for more details or he can buy the book thro PayPal. If he chooses to send you a message, a form will be displayed on page with several fields and a submit button. If the user chooses to buy the book, in page will be displayed a PayPal button (assuming that you have a PayPal account and you have generated the snippet code from your PayPal control panel). We will create in page two <div> elements, both with the property display:none, one <div> for the message form and one for the PayPal option. The user will use a <select> element to choose his options and the correspondent <div> element will be displayed in page using JavaScript. The code for our page is:

Listing 2: Code for our page

<!Doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Second Example</title>
		<style type="text/css">
			#message, #buy {
				margin-top: 30px;
				display: none;
			}
		</style>
	</head>
	<body>
		<h1>Showing and hiding elements using JavaScript</h1>
		<h3>Welcome</h3>
		<p>
			You can choose to buy our book or you can send us a message for more details.
			Thank you!
		</p>
		
		<label>Please choose your option</label>
		<select id="userOption">
			<option value="none"></option>
			<option value="message">Send us a message</option>
			<option value="buy">Buy the eBook</option>
		</select>
		<div id="message">
			<form>
				<label>Your name</label> <br />
				<input type="text" placeholder="Your name here" /> <br />
				<label>Your email</label> <br />
				<input type="text" placeholder="Your email here" /> <br />
				<label>Your message</label> <br/>
				<textarea cols="30" rows="10" placeholder="Your message here">
                                                         </textarea> <br />
				<input type="submit" value="Send your message" />
			</form>
		</div>
		<div id="buy">
			<p>Thank you for buying our eBook. You can pay the amount of $10 through PayPal.</p>
			<p>
				<img src="paypal.jpg" />
			</p>
		</div>
		<script>
			//retrieve from document the <select> element
			var userOption=document.getElementById("userOption");
			//retrieve from document first <div> element
			var message=document.getElementById("message");
			//retrieve from document second <div> element
			var buy=document.getElementById("buy");
			
			//use onChange event for <select> element
			userOption.onchange=function() {
				//retrieve the chosen option from the <select> element
				var chosenOption=this.options[this.selectedIndex];
				//display/hide <div>elements
				switch (chosenOption.value) {
					case "message":
						message.style.display="block";
						buy.style.display="none";
						break;
					case "buy":
						message.style.display="none";
						buy.style.display="block";
						break;
					default:
						message.style.display="none";
						buy.style.display="none";
				}
			}
		</script>
	</body>
</html>

As you can see from the code above, both <div> elements are the display properties set to none. I prefer using display:none; instead of visibility: hidden; because in the second case the element is just invisible and he occupies space in the document flow leaving ugly white spaces in the page. When the user choose an option from the <select> element, the onChange() event is triggered and JavaScript changes the display property of the <div> elements to block (showing the <div>), or to none (hiding the <div>).

The next image is a screenshot of our page if user chooses to send a message:

Screenshot of our page if user chooses to send a message

Figure 2: Screenshot of our page if user chooses to send a message

And this one is a screenshot of our page if user chooses to buy the eBook through PayPal:

Screenshot of our page if user chooses to buy the eBook through PayPal

Figure 3: Screenshot of our page if user chooses to buy the eBook through PayPal

In this last example we’ll use a <select> element and JavaScript to dynamically modify the content of a <span> element using the innerHTML property and the displayed image using src attribute for an img element.

Listing 3: Code for the page

<!Doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Third Example</title>
		<style type="text/css">
			#animal {
				margin-top: 30px;
				display: none;
			}
			body {
				margin-left: 50px;
			}
		</style>
	</head>
	<body>
		<h1>How to dinamically modify the content of an element using JavaScript</h1>
		<h3>Welcome</h3>
		<p>
			Please tell us which animal do you like most?
		</p>
		
		<select id="userOption">
			<option value="none"></option>
			<option value="cat">I like cats</option>
			<option value="dog">I like dogs</option>
			<option value="rabbit">I like rabbits</option>
		</select>
		<div id="animal">
			<p> Because you like <strong><span id="animalName"></span></strong> so much, 
			    we have prepared a nice picture for you.
			</p>
			<img id="animalImage" src="" height="400" width=""500" />
		</div>
		
		<script>
			//retrieve from document the <select> element
			var userOption=document.getElementById("userOption");
			//retrieve from document the <span> element
			var animalName=document.getElementById("animalName");
			//retrieve from document the <img> element
			var animalImage=document.getElementById("animalImage");
			
			//use onChange event for <select> element
			userOption.onchange=function() {
				//retrieve the chosen option from the <select> element
				var chosenOption=this.options[this.selectedIndex];
				//change the text for the <span> element, the image source for
				//the <img> element and display the <div> element
				switch (chosenOption.value) {
					case "cat":
						animalName.innerHTML="cats";
						animalImage.src="cat.jpg";
						animal.style.display="block";
						break;
					case "dog":
						animalName.innerHTML="dogs";
						animalImage.src="dog.jpg";
						animal.style.display="block";
						break;
					case "rabbit":
						animalName.innerHTML="rabbits";
						animalImage.src="rabbit.jpg";
						animal.style.display="block";
						break;
					default:
						animal.style.display="none";
				}
			}
		</script>
	</body>
</html>

And some screenshots for our page:

Changing images to cats

Figure 4: Changing images to cats

Changing images to rabbits

Figure 5: Changing images to rabbits

Conclusion

As you can see from those examples, is quite easy to manipulate the content of a web page using JavaScript and make your page interactive. So, try it yourself and use this tricks to make your website more attractive.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
Know how to keep MrBool Online
SUPPORT US
SUPPORT US
With your help, we can keep providing free content and helping you to be a better professional
support us
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually � in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits � in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login