Introduction to JavaScript
JavaScript Introduction
JavaScript and Java, despite their similar names, are entirely different. JavaScript was created in 1995 by Brendan Eich, and it became a standard known as ECMAScript in 1997. JavaScript is mostly used for web development, while Java is a programming language often used for standalone applications.
Welcome to our JavaScript introduction! JavaScript, often called "JS," is a powerful programming language that enables interactive web pages and dynamic applications. Whether you're building simple websites or complex web apps, learning JavaScript is essential.
Why Learn JavaScript?
JavaScript is a must-have skill for any web developer. It can:
- Change HTML content and attributes dynamically
- Adjust CSS styles directly within HTML
- Hide or show HTML elements based on user actions
By mastering JavaScript, you'll unlock new capabilities to create responsive, interactive websites.
JavaScript Basics: Writing "Hello World!"
Let's start with a simple JavaScript example. To print "Hello World!" on a web page, use the getElementById()
method to select an HTML element and change its content.
1<!DOCTYPE html>
2<html>
3<body>
4
5<h2>JavaScript Example</h2>
6<p id="demo">This is a paragraph.</p>
7
8<script>
9 document.getElementById("demo").innerHTML = "Hello World!";
10</script>
11
12</body>
13</html>
In this example, JavaScript finds the HTML element with id="demo"
and replaces its text content with "Hello World!" This is a quick and effective way to modify HTML using JavaScript code.
JavaScript for HTML Content
JavaScript is commonly used to change the content of HTML elements. You can assign new text or HTML code to an element's innerHTML
property, as shown here:
1document.getElementById("demo").innerHTML = "Welcome to DevsCall JavaScript!";
With JavaScript, you can use either double or single quotes around text strings:
1document.getElementById('demo').innerHTML = 'Hello JavaScript';
JavaScript Styling (CSS Integration)
JavaScript can dynamically apply CSS styles. For example, to change the font size of a paragraph:
1document.getElementById("demo").style.fontSize = "24px";
With JavaScript, you can modify various CSS properties to adjust the look and feel of web content.
Show and Hide Elements
JavaScript can hide and show HTML elements based on user interactions. For instance, hiding an element by setting its display
style to none
:
1document.getElementById("demo").style.display = "none";
To show it again, change the display
property back to block
:
1document.getElementById("demo").style.display = "block";
These simple yet powerful techniques allow you to create interactive content that responds to user actions, making the user experience more engaging.