0% found this document useful (0 votes)
2 views23 pages

Javascript Display Examples

This document outlines various methods for displaying JavaScript on webpages, including inline, internal, and external JavaScript. It also explains how to output results using methods like alert, console.log, document.write, and innerHTML. Additionally, it provides examples and mini-projects to demonstrate practical applications of JavaScript in web development.

Uploaded by

samuel asefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Javascript Display Examples

This document outlines various methods for displaying JavaScript on webpages, including inline, internal, and external JavaScript. It also explains how to output results using methods like alert, console.log, document.write, and innerHTML. Additionally, it provides examples and mini-projects to demonstrate practical applications of JavaScript in web development.

Uploaded by

samuel asefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

How to Display JavaScript

This document explains how to display JavaScript on a webpage using different methods. It includes inline
JavaScript, internal JavaScript, external JavaScript, and how to output/display results.

1. Inline JavaScript (inside HTML tags)


This is the simplest form. You use attributes like `onclick`, `onmouseover`, etc., directly in HTML.

Example:

<button onclick="alert('Hello!')">Click Me</button>


When the button is clicked, the JavaScript inside `onclick` runs and shows an alert box.

2. Internal JavaScript (using <script> tag in the same HTML file)


You write JavaScript inside a `<script>` block, usually in the `<head>` or at the end of the `<body>`.

Example:

<!DOCTYPE html>
<html>
<head>
<script>
function showMessage() {
alert("Hello from internal JavaScript!");
}
</script>
</head>
<body>

<button onclick="showMessage()">Click Me</button>


</body>
</html>
The script defines a function (`showMessage`) and HTML calls it.

3. External JavaScript File (recommended for real projects)


You save your JavaScript code in a separate `.js` file and link it using the `<script src='...'></script>` tag.

Example:

<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<button onclick="sayHi()">Click Me</button>
</body>
</html>
This links the external JavaScript file.

script.js:

function sayHi() {
alert("Hello from external JS file!");
}
This file contains the JavaScript function.

4. How to Show Output in JavaScript


Here are common ways JavaScript displays or outputs data:

Method Description Example

alert() Popup box alert('Hi!')

console.log() Shows in browser console.log('Debug info')


developer console

document.write() Writes directly into the document.write('Hello World')


page

innerHTML Changes part of the page document.getElementById('demo').innerHTML = 'Text'


content

5. Example: Show Message with All 4 Methods


Example:

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
alert("This is an alert box!");
console.log("This is logged in the console.");
document.write("This was written with document.write.<br>");
document.getElementById("demo").innerHTML = "This text was added to a paragraph.";
</script>
</body>
</html>
This example demonstrates all four methods of displaying output.

Skip to content

Open sidebar

<!DOCTYPE html>

<html>

<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>

</html>

🔹 What is JavaScript and What Can It Do?

JavaScript is a programming language used to make web pages interactive. It can:

 Change HTML content


 Change HTML attributes (like the src of an image)
 Change CSS styles
 React to events (like button clicks)
 Validate forms
 Make calculations
 And much more...

🔹 Where to Write JavaScript in HTML?

There are three main ways to add JavaScript to your HTML file:

✅ 1. Inline JavaScript (inside HTML tags) Like in your example:


<button onclick="alert('Hello!')">Click me</button>

✅ 2. Internal JavaScript (using <script> in the HTML file)

You can write JavaScript in the <head> or at the bottom of <body> using the <script> tag:

<!DOCTYPE html>

<html>

<head>

<title>Internal JavaScript Example</title>

<script>

function turnOn() {

document.getElementById("myImage").src = "pic_bulbon.gif";

function turnOff() {

document.getElementById("myImage").src = "pic_bulboff.gif";

</script>

</head>

<body>

<h2>What Can JavaScript Do?</h2>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<br><br>

<button onclick="turnOn()">Turn on the light</button>

<button onclick="turnOff()">Turn off the light</button>

</body>

</html>

✅ 3. External JavaScript File (recommended for big projects)

Create a file like script.js and link it in HTML:


script.js

function turnOn() {

document.getElementById("myImage").src = "pic_bulbon.gif";

function turnOff() {

document.getElementById("myImage").src = "pic_bulboff.gif";

index.html

<!DOCTYPE html>

<html>

<head>

<title>External JS Example</title>

<script src="script.js"></script>

</head>

<body>

<h2>Using External JavaScript</h2>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<br><br>

<button onclick="turnOn()">Turn on the light</button>

<button onclick="turnOff()">Turn off the light</button>

</body>

</html>

🔹 Now, Let’s See More JavaScript Examples

💡 1. Change Text with JavaScript

<p id="demo">Hello</p>

<button onclick="document.getElementById('demo').innerHTML = 'Goodbye'">Change Text</button>


🎨 2. Change CSS Style with JavaScript

<p id="demo2">Watch my color change!</p>

<button onclick="document.getElementById('demo2').style.color = 'red'">Change Color</button>

📦 3. Hide and Show Elements

<p id="demo3">You can hide me!</p>

<button onclick="document.getElementById('demo3').style.display='none'">Hide</button>

<button onclick="document.getElementById('demo3').style.display='block'">Show</button>

🔹 Why Your First Code Doesn’t Use <script>?

Your code is using inline JavaScript, where the JavaScript is directly inside the onclick attribute. That’s
perfectly okay for small examples but for better organization and readability, <script> is preferred.

🔹 How to Run HTML, CSS, and JavaScript?

You can run them in:

A browser (Chrome, Firefox, Edge, etc.)

An online editor like: JSFiddle ,CodePen ,JSBin

Using Notepad or VS Code: Save as .html

✅ Project: "Interactive Light Bulb"

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Interactive Light Bulb</title>

<!-- CSS Styling -->

<style>

body {

text-align: center;

font-family: Arial, sans-serif;

background-color: #f4f4f4;
padding-top: 50px;

h1 {

color: #333;

#myImage {

width: 120px;

margin: 20px;

border: 3px solid #555;

border-radius: 10px;

button {

padding: 10px 20px;

margin: 10px;

font-size: 16px;

border: none;

border-radius: 5px;

background-color: #007bff;

color: white;

cursor: pointer;

button:hover {

background-color: #0056b3;

#statusText {

font-size: 18px;
margin-top: 20px;

</style>

</head>

<body>

<!-- HTML Content -->

<h1>Control the Light Bulb</h1>

<img id="myImage" src="pic_bulboff.gif" alt="Light Bulb">

<div>

<button onclick="turnOn()">Turn On</button>

<button onclick="turnOff()">Turn Off</button>

</div>

<p id="statusText">The bulb is OFF.</p>

<!-- JavaScript Section -->

<script>

function turnOn() {

document.getElementById("myImage").src = "pic_bulbon.gif";

document.getElementById("statusText").innerHTML = "The bulb is ON.";

function turnOff() {

document.getElementById("myImage").src = "pic_bulboff.gif";

document.getElementById("statusText").innerHTML = "The bulb is OFF.";

</script>

</body>
</html>

🔸 2. How It Works – Explanation

✅ HTML Section

<h1>Control the Light Bulb</h1>

<img id="myImage" src="pic_bulboff.gif" alt="Light Bulb">

<button onclick="turnOn()">Turn On</button>

<button onclick="turnOff()">Turn Off</button>

<p id="statusText">The bulb is OFF.</p>

img: Shows the bulb image.

id="myImage": Gives the image an ID so JavaScript can find and change it.

onclick="turnOn()": Calls the JavaScript function turnOn() when clicked.

✅ CSS Section (<style>)

body, h1, button {

/* Styles for background, text, buttons */

CSS makes the page look nice: colors, spacing, fonts, hover effects.

✅ JavaScript Section (<script>)

function turnOn() {

document.getElementById("myImage").src = "pic_bulbon.gif";

document.getElementById("statusText").innerHTML = "The bulb is ON.";

document.getElementById("..."): Finds the element using its ID.


.src = "...": Changes the image file.

.innerHTML = "...": Changes the text content.

🔸 3. How to Run

Save this code in a file: bulb.html

Download two images:

pic_bulboff.gif (bulb off image)

pic_bulbon.gif (bulb on image)

Put all in the same folder

Double-click the HTML file to open it in a browser!

🔸 4. Want More Projects?

Would you like a second mini-project like a calculator, clock, or color changer to practice further?

You said:

Yes continue

ChatGPT said:

Awesome! Let’s continue with a second mini-project that’s simple, visual, and fun to practice with. We’ll make
a "Color Changer Box" where clicking a button changes the background color randomly.
✅ Project 2: Random Background Color Changer

🔸 1. Full Code (HTML + CSS + JavaScript)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Random Color Changer</title>

<!-- CSS Styling -->

<style>

body {

text-align: center;

font-family: 'Segoe UI', sans-serif;

margin-top: 50px;

background-color: #f0f0f0;

#colorBox {

width: 300px;

height: 200px;

margin: 30px auto;

border: 5px solid #444;

border-radius: 10px;

background-color: white;

display: flex;

align-items: center;

justify-content: center;
font-size: 20px;

font-weight: bold;

button {

padding: 12px 25px;

font-size: 16px;

border: none;

border-radius: 5px;

background-color: #28a745;

color: white;

cursor: pointer;

button:hover {

background-color: #218838;

</style>

</head>

<body>

<h1>Random Color Changer</h1>

<div id="colorBox">Click the button!</div>

<button onclick="changeColor()">Change Color</button>

<!-- JavaScript -->

<script>

function changeColor() {

// Generate a random hex color

let randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);


// Set the color to the box

document.getElementById('colorBox').style.backgroundColor = randomColor;

// Show the color code in the box

document.getElementById('colorBox').innerHTML = randomColor.toUpperCase();

</script>

</body>

</html>

🔸 2. Explanation

✅ HTML

<div id="colorBox">Click the button!</div>

<button onclick="changeColor()">Change Color</button>

div#colorBox: A box whose background color we change.

button: Calls the changeColor() function when clicked.

✅ JavaScript

let randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);

This line generates a random hex color like #3fa9f5.

document.getElementById('colorBox').style.backgroundColor = randomColor;

Applies the random color to the box’s background.

document.getElementById('colorBox').innerHTML = randomColor.toUpperCase();

Displays the hex code inside the box.

Click the button and watch the color (and color code) change.

✅ Project 3: Live Digital Clock

🔸 1. Full Code (HTML + CSS + JavaScript)

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Live Digital Clock</title>

<!-- CSS Styling -->

<style>

body {

background-color: #222;

color: #fff;

font-family: 'Segoe UI', sans-serif;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

margin: 0;

flex-direction: column;

h1 {

margin-bottom: 20px;

color: #00ffcc;

#clock {

font-size: 60px;

padding: 20px 40px;

background-color: #333;

border-radius: 10px;
box-shadow: 0 0 20px rgba(0,255,204,0.5);

letter-spacing: 4px;

</style>

</head>

<body>

<h1>Live Digital Clock</h1>

<div id="clock">00:00:00</div>

<!-- JavaScript -->

<script>

function updateClock() {

const now = new Date();

let hours = now.getHours();

let minutes = now.getMinutes();

let seconds = now.getSeconds();

// Add leading zeros if needed

hours = hours < 10 ? "0" + hours : hours;

minutes = minutes < 10 ? "0" + minutes : minutes;

seconds = seconds < 10 ? "0" + seconds : seconds;

// Format the time

const timeString = hours + ":" + minutes + ":" + seconds;

// Display it

document.getElementById("clock").innerHTML = timeString;

// Update every 1 second

setInterval(updateClock, 1000);
// Run once immediately

updateClock();

</script>

</body>

</html>

🔸 2. How It Works – Explanation

✅ HTML

<div id="clock">00:00:00</div>

A div that displays the clock time.

✅ CSS

#clock {

font-size: 60px;

background-color: #333;

padding: 20px;

Styles the clock with a glowing effect and readable font.

✅ JavaScript

setInterval(updateClock, 1000);

Runs the updateClock() function every 1000 milliseconds (1 second).

const now = new Date();

Gets the current time.

hours = hours < 10 ? "0" + hours : hours;

Ensures two-digit format like 07:09:05 instead of 7:9:5.

Save the code as digital-clock.html.

Open it in any browser.


The time will update every second!

✅ Example: Inline JavaScript to Show an Alert

<!DOCTYPE html>

<html>

<body>

<h2>Inline JavaScript Example</h2>

<button onclick="alert('Hello from inline JavaScript!')">Click Me</button>

</body>

</html>

🔍 What’s happening here?

onclick="alert('...')" is the inline JavaScript.

When the button is clicked, the alert() function is executed.

No <script> tag is used here.

✅ Example: Change Text Inline

<!DOCTYPE html>

<html>

<body>

<h2>Change Text Example</h2>

<p id="demo">This is a paragraph.</p>

<button onclick="document.getElementById('demo').innerHTML='You changed me!'">Click to Change


Text</button>

</body>

</html>

✅ Explanation:

onclick="..." directly runs JS code inside the button tag.


It accesses the <p> with id="demo" and updates its content.

⚠️Should You Use Inline JavaScript?

✅ Good for:

Simple learning

Quick testing or small tasks

❌ Not recommended for:

Large or serious projects

When you want to reuse code or keep it clean

👉 Instead, use:<script> tags in HTML Or link external .js files

Example: Light Bulb Toggle

<!DOCTYPE html>

<html>

<body>

<h2>Toggle Image Example (Inline JS)</h2>

<img id="bulb" src="pic_bulboff.gif" style="width:100px"><br><br>

<button onclick="document.getElementById('bulb').src='pic_bulbon.gif'">TurnON</button>

<buttononclick="document.getElementById('bulb').src='pic_bulboff.gif'">TurnOFF</button>

</body>

</html>

Explanation:

The img tag has an id="bulb".

The inline JavaScript inside the onclick attribute changes the image’s src.

Note: You must have pic_bulboff.gif and pic_bulbon.gif in your project folder.

✅ 2. Simple Input Validation (Inline JS)

Let’s create a form that checks if the name input is empty when you click "Submit".

Example: Name Required Validation


<!DOCTYPE html>

<html>

<body>

<h2>Inline JavaScript Input Validation</h2>

<form onsubmit="return validateForm()">

Name: <input type="text" id="name"><br><br>

<input type="submit" value="Submit">

</form>

<script>

function validateForm() {

let name = document.getElementById("name").value;

if (name === "") {

alert("Please enter your name!");

return false; // stop form submission

alert("Form submitted successfully!");

return true; // allow form submission

</script>

</body>

</html>

Explanation:

Form has onsubmit="return validateForm()" — this calls the validateForm() JavaScript function.

If the input is empty, it shows an alert and stops the form.

Otherwise, it continues and shows a success alert.

✅ 1. Inline JavaScript (inside HTML tags)


This is the simplest form. You use attributes like onclick, onmouseover, etc., directly in HTML.

Example:

<button onclick="alert('Hello!')">Click Me</button>

When the button is clicked, the JavaScript inside onclick runs and shows an alert box.

✅ 2. Internal JavaScript (using <script> tag in the same HTML file)

You write JavaScript inside a <script> block, usually in the <head> or at the end of the <body>.

Example:

<!DOCTYPE html>

<html>

<head>

<script>

function showMessage() {

alert("Hello from internal JavaScript!");

</script>

</head>

<body>

<button onclick="showMessage()">Click Me</button>

</body>

</html>

The script defines a function (showMessage) and HTML calls it.

✅ 3. External JavaScript File (recommended for real projects)

You save your JavaScript code in a separate .js file and link it using the <script src="..."></script> tag.

index.html

<!DOCTYPE html>
<html>

<head>

<script src="script.js"></script>

</head>

<body>

<button onclick="sayHi()">Click Me</button>

</body>

</html>

script.js

function sayHi() {

alert("Hello from external JS file!");

Keeps your code clean and organized.

You can reuse script.js in multiple pages.

✅ How to Show Output in JavaScript

Here are common ways JavaScript displays or outputs:

Method Description Example

alert() Popup box alert("Hi!")

console.log() Shows in browser developer console console.log("Debug info")

document.write() Writes directly into the page document.write("Hello World")

innerHTML Changes part of the page content document.getElementById("demo").innerHTML =


"Text"

🛠 Example: Show Message with All 4 Methods

<!DOCTYPE html>
<html>

<body>

<p id="demo"></p>

<script>

alert("This is an alert box!");

console.log("This is logged in the console.");

document.write("This was written with document.write.<br>");

document.getElementById("demo").innerHTML = "This text was added to a paragraph.";

</script>

</body>

</html>

Would you like a practice file to try all of these? Or shall I guide you in setting up your own .js file and
connecting it to HTML?

You said:

Please write this flle in docx file format . I need to download and edit without reduse with Formatting

ChatGPT said:

I've created the document with all the examples and explanations you requested. You can download it using
the link below:

Download JavaScript Display Examples

Feel free to edit it as needed! Let me know if you need any further assistance.
No file chosenNo file chosen

ChatGPT can make mistakes. Check important info.

You might also like