Sunday 19 April 2015

JavaScript in HTML

JavaScript is mainly used to manipulate the HTML elements. JavaScript gives us the full freedom to add interactivity and responsiveness to our web page. As all of you know, HTML is used to give a structure to our web page and CSS is used to change the appearance of our page. But do you know why JavaScript is used? If you don't there is no problem. JavaScript is a web programming language that enables us to control how a webpage behaves. This make this language very crucial in web designing. Using JavaScript, we can do many things such as:
  • Put text in HTML page anytime.
  • Make your web page responsive and efficient.
  • Used to detect visitor's browser.
  • Create cookies
  • Validate Form
  • and much more.

Writing JavaScript code

Writing a JavaScript code is easy but one simple mistake can lead you to scratching your head. So whenever you type a code be sure that the code you are writing is completely perfect. JavaScript code is written between the <script> tag. A JavaScript code starts with document.write and the code is written between a pair of parenthesis. Note that, when you execute a text using document.write on a HTML page, the HTML element will be overwritten.

For example:
<!DOCTYPE html>
<html>

<body>
<h1>My Webpage</h1>

<script>
document.write("<p>My first JavaScript text</p>");
</script>

</body>
</html>

We can also write a document.write code by calling out a function.

For example:
<!DOCTYPE html>
<html>

<body>
<h1>My Webpage</h1>

<script>
function myFunction()
{
document.write("<p>My first JavaScript text</p>");
}
</script>

<button onclick="myFunction()">Try it<button> 

</body>
</html>

Accessing a HTML element

To access a HTML element, we use the document.getelementById() method. We use the id attribute to denote which HTML element to be accessed upon.

For example:
<!DOCTYPE html>
<html>

<body>
<h1>My Webpage</h1>
<p id="demo">A paragraph</h1>

<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My JavaScript text";
}
</script>

<button type="button" onclick="myFunction()">Try it<button> 

</body>
</html>

0 comments:

Post a Comment