Displaying contents in a Div
This tutorial will teach you how to display a text,image and a link in a div using javascript.
For this we will introduce the use of innerHTML.
function ShowLink()
{
document.getElementById('mydiv').innerHTML="<a href='https://www.facebook.com'>
Go to Facebook!</a>";
}
For this we will introduce the use of innerHTML.
What is innerHTML?
- innerHTML sets or returns a content inside/within an html tag.
- It can be used to set/return contents such as a link,image and text.
Example 1:
Displaying Text in a div:
The form appears as shown in screenshot on left.
Clicking Show Text button displays the text in a div.(see screenshot on right).
Complete Code for Form:
<html>
<head>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<form name='frm'>
<div style='border:solid;1px;width:170px;height:30px;' id='mydiv'></div>
<p> <input type='button' name='btnshow' value='Show Text' onclick='ShowText()'/></p>
</form>
</body>
</html>
Code Explained:
- The id of the div is set.In our case,it is 'mydiv'; highligted in red.
- The button 'Show Text' calls the Javascript function ShowText() on click.
- The external.js is included between head tag.
Complete Code for external.js:
function ShowText()
{
document.getElementById('mydiv').innerHTML="Am a text displayed in a div";
}
Code Explained:
innerHTML sets/returns the text "Am a text displayed in a div" within the HTML tag with id mydiv.
Example 2:
Displaying Image in a div:
The form appears as shown in screenshot on left.
Clicking Show Image button displays the Image in a div.(see screenshot on right).
Complete Code for Form:
<html>
<head>
<script type='text/javascript' src='external2.js'></script>
</head>
<body>
<form name='frm'>
<div style='border:solid;1px;width:60px;height:60px;' id='mydiv'></div>
<p> <input type='button' name='btnshow' value='Show Image' onclick='ShowImage()'/></p>
</form>
</body>
</html>
Complete Code for external2.js:
function ShowImage()
{
document.getElementById('mydiv').innerHTML="<img src='myimage.jpg' alt='image'/>";
}
Download myimage.jp here(right-click and save as)
Example 3:
Displaying Link in a div:
Complete Code for Form:
<html>
<head>
<script type='text/javascript' src='external3.js'></script>
</head>
<body>
<form name='frm'>
<div style='border:solid;1px;width:170px;height:30px;' id='mydiv'></div>
<p> <input type='button' name='btnshow' value='Show Link' onclick='ShowLink()'/></p>
</form>
</body>
</html>
Complete Code for external3.js:
function ShowLink()
{
document.getElementById('mydiv').innerHTML="<a href='https://www.facebook.com'>
Go to Facebook!</a>";
}





No comments:
Post a Comment