JavaScript Introduction
JavaScript is the programming language that brings web pages to life.
What is JavaScript?
- JavaScript is a programming language that runs in the web browser
- It can change the HTML and CSS of a page after the page has loaded
- It can react to what the user does, like clicks, typing and scrolling
- It is not the same as Java. The names are similar, but they are two different languages
Think of a website as a house. HTML is the walls and rooms, CSS is the paint and furniture, and JavaScript is the electricity: it makes the lights, fans and doorbell work.
JavaScript Can Change Text
In this example, JavaScript finds the paragraph with id="demo" and changes its text when you click the button.
Example
<!DOCTYPE html>
<html>
<body>
<h2>Ali's Notice Board</h2>
<p id="demo">Class starts at 9 AM.</p>
<button onclick="document.getElementById('demo').innerHTML = 'Class moved to 10 AM!'">Update notice</button>
</body>
</html>Try it Yourself »document.getElementById("demo") finds the element. .innerHTML is its content, and we give it new text.
JavaScript Can Change Styles
JavaScript can also change CSS. Here a button makes the text bigger and green.
Example
<!DOCTYPE html>
<html>
<body>
<p id="price">Biryani: Rs 350</p>
<button onclick="document.getElementById('price').style.fontSize = '30px'; document.getElementById('price').style.color = 'green';">Highlight price</button>
</body>
</html>Try it Yourself »JavaScript Can Hide and Show Elements
Example
<!DOCTYPE html>
<html>
<body>
<p id="secret">Today's discount code: KHI10</p>
<button onclick="document.getElementById('secret').style.display = 'none'">Hide</button>
<button onclick="document.getElementById('secret').style.display = 'block'">Show</button>
</body>
</html>Try it Yourself »What Can JavaScript Do?
| Task | Example |
|---|---|
| Change content | Update a price or a message |
| Check forms | Warn if the phone number is empty |
| React to events | Open a menu when a button is clicked |
| Load data | Show new results without reloading the page |
| Make games and animations | Move objects on the screen |
JavaScript is case sensitive. getElementById works, but getElementByID does not.
A Short History
| Year | Event |
|---|---|
| 1995 | Brendan Eich creates JavaScript in about 10 days |
| 1997 | It becomes a standard called ECMAScript |
| 2015 | ES6 (ECMAScript 2015) adds many modern features |
| Today | A new version is released every year |
This tutorial teaches modern JavaScript that works in all current browsers.
Exercise
Exercise
Which statement about JavaScript and Java is correct?
