Mark As Completed Discussion

Working with JavaScript

JavaScript allows editing and modifying HTML content and CSS styles. Let's understand how JavaScript brings interactivity to websites by an example.

Consider a website with some hidden content. We can use JavaScript to display this hidden content once the user interacts with an HTML element (here, a button) on the page.

Working with JavaScript

The HTML code for this example will be,

SNIPPET
1<!DOCTYPE html>
2<html>
3<head>
4<link rel="stylesheet" href="style.css">
5<script src="script.js"></script>
6</head>
7<body>
8<h1> JavaScript Example </h1>
9<p> This is a JavaScript example </p>
10<p id="example"> This is a hidden sentence </p>
11<button type="button" onclick="display()">Show</button>
12</body>
13</html>

CSS stylesheet

SNIPPET
1#example{
2    display: none;
3}

JavaScript code

SNIPPET
1function display(){
2    document.getElementbyId('example').style.display = "block"
3}

Here, we assign a JavaScript function to the onclick attribute of the button HTML tag. This attribute specifies that the display() function from the script should be called once the user clicks the button. The JavaScript function gets the hidden element from its ID and changes its display style to show the hidden content. The hidden text then becomes visible.

Working with JavaScript

This example shows one of the many things that JavaScript can do. Many libraries have also been developed in JavaScript to make it easier to perform various tasks on the web.