How To Include Javascript In A Webpage (2) - JavaScript for the Front End
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

How to Include JavaScript in a Webpage

How to Include JavaScript in a Webpage

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

What is Inline JavaScript?

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, we're starting with inline JavaScript, which allows you to add behavior directly to HTML elements using event attributes like `onclick`. Can anyone tell me what happens when you click this button?

Student 1
Student 1

It shows a message, right?

Teacher
Teacher Instructor

Exactly! For example, `<button onclick="alert('Hello!')">Click Me</button>` will show a message box when clicked. While it's straightforward, it's not the best practice for larger projects. Can anyone think of why?

Student 2
Student 2

Maybe because it mixes HTML and JavaScript?

Teacher
Teacher Instructor

Yes! That's a very good point. We want our code to be organized. Let's move on to the next method, internal JavaScript.

Exploring Internal JavaScript

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now, let's talk about internal JavaScript, which allows you to place code inside a `<script>` tag in your HTML. This keeps your code more structured. For instance: `<script> document.getElementById('myButton').onclick = function() { alert('You clicked the button!'); }; </script>`.

Student 3
Student 3

So, this way, we can have multiple functions or scripts organized together?

Teacher
Teacher Instructor

Correct! It makes the HTML file neater. Why do you think it's better than inline JavaScript?

Student 4
Student 4

Because we can easily find and edit our scripts without mixing them with HTML content.

Teacher
Teacher Instructor

Exactly! Internal scripts help separate concerns. Now let's dive into external JavaScript.

Understanding External JavaScript

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

External JavaScript gives us the best organization. You write your JavaScript in a separate `.js` file and link it to your HTML using `<script src='script.js'></script>`. What could be the advantages of this approach?

Student 1
Student 1

We can reuse the same JavaScript file in different HTML files!

Teacher
Teacher Instructor

Correct! Reusability is a big advantage. It also keeps our HTML clean, which is essential in larger projects. Can someone tell me how this affects maintenance?

Student 3
Student 3

If there's a bug, we can just fix it in one place instead of changing it in multiple HTML files.

Teacher
Teacher Instructor

Exactly! Less room for error and easier updates. Can anyone summarize the three inclusion methods we discussed today?

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

This section explains the various ways to include JavaScript in a webpage, enhancing interactivity and functionality.

Standard

In this section, you'll learn how to integrate JavaScript into your webpages using inline, internal, and external methods. Each approach is discussed with examples that illustrate how JavaScript links to HTML to create dynamic user experiences.

Detailed

How to Include JavaScript in a Webpage

JavaScript is an essential tool for adding interactivity to webpages. This section outlines three primary methods of incorporating JavaScript into HTML documents: inline JavaScript, internal JavaScript, and external JavaScript, each with its own use cases and best practices.

Inline JavaScript

Inline JavaScript allows you to embed scripts directly within HTML tags using event attributes like onclick. For example:

Code Editor - html

Though convenient for small scripts, inline JavaScript is discouraged for larger projects to keep structure and behavior separate.

Internal JavaScript

You can add JavaScript inside the <script> tag within the HTML file. For example:

Code Editor - html
`, -1); codePreviewd9143ae18b6f4a8ca55b1b196081aefb.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-d9143ae18b6f4a8ca55b1b196081aefb`).addEventListener('click', () => { switchToEditord9143ae18b6f4a8ca55b1b196081aefb(); }); function switchToEditord9143ae18b6f4a8ca55b1b196081aefb() { // Initialize the editor editord9143ae18b6f4a8ca55b1b196081aefb = ace.edit("d9143ae18b6f4a8ca55b1b196081aefb") setLanguaged9143ae18b6f4a8ca55b1b196081aefb(languaged9143ae18b6f4a8ca55b1b196081aefb); editord9143ae18b6f4a8ca55b1b196081aefb.setValue(``, -1); initEditorSettingsd9143ae18b6f4a8ca55b1b196081aefb(); attachEventListenersd9143ae18b6f4a8ca55b1b196081aefb(); document.getElementById(`editor-container-d9143ae18b6f4a8ca55b1b196081aefb`).classList.remove('hidden'); document.getElementById(`preview-container-d9143ae18b6f4a8ca55b1b196081aefb`).classList.add('hidden'); } function switchToPreviewd9143ae18b6f4a8ca55b1b196081aefb() { // Clean up the editor instance editord9143ae18b6f4a8ca55b1b196081aefb.destroy(); editord9143ae18b6f4a8ca55b1b196081aefb = null; document.getElementById(`editor-container-d9143ae18b6f4a8ca55b1b196081aefb`).classList.add('hidden'); document.getElementById(`preview-container-d9143ae18b6f4a8ca55b1b196081aefb`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-d9143ae18b6f4a8ca55b1b196081aefb`).addEventListener('click', () => { switchToEditord9143ae18b6f4a8ca55b1b196081aefb(); }); } function initEditorSettingsd9143ae18b6f4a8ca55b1b196081aefb() { editord9143ae18b6f4a8ca55b1b196081aefb.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editord9143ae18b6f4a8ca55b1b196081aefb.setTheme('ace/theme/xcode'); editord9143ae18b6f4a8ca55b1b196081aefb.session.setMode(`ace/mode/${languaged9143ae18b6f4a8ca55b1b196081aefb}`); } function setLanguaged9143ae18b6f4a8ca55b1b196081aefb(lang) { languaged9143ae18b6f4a8ca55b1b196081aefb = lang; editord9143ae18b6f4a8ca55b1b196081aefb.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCoded9143ae18b6f4a8ca55b1b196081aefb(code) { editord9143ae18b6f4a8ca55b1b196081aefb.setValue(code, -1); } function toggleThemed9143ae18b6f4a8ca55b1b196081aefb() { const isDarkMode = editord9143ae18b6f4a8ca55b1b196081aefb.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-d9143ae18b6f4a8ca55b1b196081aefb`); const moonIcon = document.getElementById(`moon-icon-d9143ae18b6f4a8ca55b1b196081aefb`); if (isDarkMode) { editord9143ae18b6f4a8ca55b1b196081aefb.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editord9143ae18b6f4a8ca55b1b196081aefb.setTheme('ace/theme/monokai'); sunIcon.classList.add('hidden'); moonIcon.classList.remove('hidden'); } } function removeTrailingSpaces(base64String) { // Trim the string to remove any trailing newline characters return btoa(atob(base64String).trim()); } async function runCoded9143ae18b6f4a8ca55b1b196081aefb() { const code = btoa(editord9143ae18b6f4a8ca55b1b196081aefb.getValue()); const stdIn = btoa(document.getElementById("input-d9143ae18b6f4a8ca55b1b196081aefb").value); const loader = document.getElementById(`run-loader-d9143ae18b6f4a8ca55b1b196081aefb`); const output = document.getElementById(`output-d9143ae18b6f4a8ca55b1b196081aefb`); const outputContainer = document.getElementById(`run-output-d9143ae18b6f4a8ca55b1b196081aefb`); const batchOutputContainer = document.getElementById(`batch-run-output-d9143ae18b6f4a8ca55b1b196081aefb`); loader.classList.remove('hidden'); outputContainer.classList.remove('hidden'); output.innerHTML = ''; try { const response = await fetch('/code/api/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: languaged9143ae18b6f4a8ca55b1b196081aefb, language_id: getLanguageIdd9143ae18b6f4a8ca55b1b196081aefb(languaged9143ae18b6f4a8ca55b1b196081aefb), source_code: code, std_in: stdIn, submission_type: 'run', test_cases: [] || [], }), }); const codeResult = await response.json(); if (Array.isArray(codeResult)) { outputContainer.classList.add("hidden"); batchOutputContainer.classList.remove("hidden"); batchOutputContainer.innerHTML = `
${codeResult?.map((result, index) => { const testCaseStatus = result.is_public ? removeTrailingSpaces(result.stdout) === result.expected_output : result.status; return `
${testCaseStatus ? `` : ``} Test Case ${index + 1} ${!result.is_public ? `` : ``}
`; }) .join("")}
${codeResult && codeResult[0] ? atob(codeResult[0].stdin) : "No input available"}
${codeResult && codeResult[0] ? atob(codeResult[0].expected_output) : "No expected output available"}
${codeResult?.[0]?.stderr || codeResult[0].compile_output ? atob(codeResult[0].stderr || codeResult[0].compile_output) : codeResult?.[0] ? (codeResult[0].stdout == null ? "" : atob(codeResult[0].stdout)) : "No output available"}
`; codeResult?.forEach((result, index) => { const codeResult = result; document.getElementById(`testCase-${index}`).addEventListener("click", () => { Array.from(document.querySelectorAll('[id*="testCase"]'))?.map(testCase => { if (testCase.id === `testCase-${index}`) { testCase.classList.add("lg:scale-105", "border", "border-gray-200"); testCase.classList.remove("scale-100", "border-none"); } else { testCase.classList.add("scale-100", "border-none"); testCase.classList.remove("lg:scale-105", "border", "border-gray-200"); } }) if (!result.is_public) { document.getElementById("test-result").innerHTML = `

Hidden Test Case

` return; } document.getElementById("test-result").innerHTML = `
${codeResult ? atob(codeResult.stdin) : "No input available"}
${codeResult ? atob(codeResult.expected_output) : "No expected output available"}
${codeResult ? (codeResult.stderr || codeResult.compile_output ? atob(codeResult.stderr || codeResult.compile_output) : codeResult.stdout == null ? "" : atob(codeResult.stdout)) : "No output available"}
`; }); }); } else { batchOutputContainer.classList.add("hidden") outputContainer.classList.remove('hidden') output.textContent = codeResult.stderr ? atob(codeResult.stderr) : atob(codeResult.stdout || ''); } } catch (error) { console.error(error); } finally { loader.classList.add('hidden'); } } function getLanguageIdd9143ae18b6f4a8ca55b1b196081aefb(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListenersd9143ae18b6f4a8ca55b1b196081aefb() { document .getElementById(`theme-toggle-d9143ae18b6f4a8ca55b1b196081aefb`) .addEventListener('click', toggleThemed9143ae18b6f4a8ca55b1b196081aefb); document .getElementById(`run-code-d9143ae18b6f4a8ca55b1b196081aefb`) .addEventListener('click', runCoded9143ae18b6f4a8ca55b1b196081aefb); document .getElementById(`view-preview-d9143ae18b6f4a8ca55b1b196081aefb`) .addEventListener('click', switchToPreviewd9143ae18b6f4a8ca55b1b196081aefb); }

This method allows for more organized code and is easier to manage than inline code.

External JavaScript

External JavaScript offers the most organization by placing code in separate .js files. This is useful for larger projects and leads to better separation of concerns. For example:

Code Editor - html
`, -1); codePreview8a4324e19cc34723ae4b9912a91f338d.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-8a4324e19cc34723ae4b9912a91f338d`).addEventListener('click', () => { switchToEditor8a4324e19cc34723ae4b9912a91f338d(); }); function switchToEditor8a4324e19cc34723ae4b9912a91f338d() { // Initialize the editor editor8a4324e19cc34723ae4b9912a91f338d = ace.edit("8a4324e19cc34723ae4b9912a91f338d") setLanguage8a4324e19cc34723ae4b9912a91f338d(language8a4324e19cc34723ae4b9912a91f338d); editor8a4324e19cc34723ae4b9912a91f338d.setValue(``, -1); initEditorSettings8a4324e19cc34723ae4b9912a91f338d(); attachEventListeners8a4324e19cc34723ae4b9912a91f338d(); document.getElementById(`editor-container-8a4324e19cc34723ae4b9912a91f338d`).classList.remove('hidden'); document.getElementById(`preview-container-8a4324e19cc34723ae4b9912a91f338d`).classList.add('hidden'); } function switchToPreview8a4324e19cc34723ae4b9912a91f338d() { // Clean up the editor instance editor8a4324e19cc34723ae4b9912a91f338d.destroy(); editor8a4324e19cc34723ae4b9912a91f338d = null; document.getElementById(`editor-container-8a4324e19cc34723ae4b9912a91f338d`).classList.add('hidden'); document.getElementById(`preview-container-8a4324e19cc34723ae4b9912a91f338d`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-8a4324e19cc34723ae4b9912a91f338d`).addEventListener('click', () => { switchToEditor8a4324e19cc34723ae4b9912a91f338d(); }); } function initEditorSettings8a4324e19cc34723ae4b9912a91f338d() { editor8a4324e19cc34723ae4b9912a91f338d.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editor8a4324e19cc34723ae4b9912a91f338d.setTheme('ace/theme/xcode'); editor8a4324e19cc34723ae4b9912a91f338d.session.setMode(`ace/mode/${language8a4324e19cc34723ae4b9912a91f338d}`); } function setLanguage8a4324e19cc34723ae4b9912a91f338d(lang) { language8a4324e19cc34723ae4b9912a91f338d = lang; editor8a4324e19cc34723ae4b9912a91f338d.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCode8a4324e19cc34723ae4b9912a91f338d(code) { editor8a4324e19cc34723ae4b9912a91f338d.setValue(code, -1); } function toggleTheme8a4324e19cc34723ae4b9912a91f338d() { const isDarkMode = editor8a4324e19cc34723ae4b9912a91f338d.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-8a4324e19cc34723ae4b9912a91f338d`); const moonIcon = document.getElementById(`moon-icon-8a4324e19cc34723ae4b9912a91f338d`); if (isDarkMode) { editor8a4324e19cc34723ae4b9912a91f338d.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editor8a4324e19cc34723ae4b9912a91f338d.setTheme('ace/theme/monokai'); sunIcon.classList.add('hidden'); moonIcon.classList.remove('hidden'); } } function removeTrailingSpaces(base64String) { // Trim the string to remove any trailing newline characters return btoa(atob(base64String).trim()); } async function runCode8a4324e19cc34723ae4b9912a91f338d() { const code = btoa(editor8a4324e19cc34723ae4b9912a91f338d.getValue()); const stdIn = btoa(document.getElementById("input-8a4324e19cc34723ae4b9912a91f338d").value); const loader = document.getElementById(`run-loader-8a4324e19cc34723ae4b9912a91f338d`); const output = document.getElementById(`output-8a4324e19cc34723ae4b9912a91f338d`); const outputContainer = document.getElementById(`run-output-8a4324e19cc34723ae4b9912a91f338d`); const batchOutputContainer = document.getElementById(`batch-run-output-8a4324e19cc34723ae4b9912a91f338d`); loader.classList.remove('hidden'); outputContainer.classList.remove('hidden'); output.innerHTML = ''; try { const response = await fetch('/code/api/run', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ language: language8a4324e19cc34723ae4b9912a91f338d, language_id: getLanguageId8a4324e19cc34723ae4b9912a91f338d(language8a4324e19cc34723ae4b9912a91f338d), source_code: code, std_in: stdIn, submission_type: 'run', test_cases: [] || [], }), }); const codeResult = await response.json(); if (Array.isArray(codeResult)) { outputContainer.classList.add("hidden"); batchOutputContainer.classList.remove("hidden"); batchOutputContainer.innerHTML = `
${codeResult?.map((result, index) => { const testCaseStatus = result.is_public ? removeTrailingSpaces(result.stdout) === result.expected_output : result.status; return `
${testCaseStatus ? `` : ``} Test Case ${index + 1} ${!result.is_public ? `` : ``}
`; }) .join("")}
${codeResult && codeResult[0] ? atob(codeResult[0].stdin) : "No input available"}
${codeResult && codeResult[0] ? atob(codeResult[0].expected_output) : "No expected output available"}
${codeResult?.[0]?.stderr || codeResult[0].compile_output ? atob(codeResult[0].stderr || codeResult[0].compile_output) : codeResult?.[0] ? (codeResult[0].stdout == null ? "" : atob(codeResult[0].stdout)) : "No output available"}
`; codeResult?.forEach((result, index) => { const codeResult = result; document.getElementById(`testCase-${index}`).addEventListener("click", () => { Array.from(document.querySelectorAll('[id*="testCase"]'))?.map(testCase => { if (testCase.id === `testCase-${index}`) { testCase.classList.add("lg:scale-105", "border", "border-gray-200"); testCase.classList.remove("scale-100", "border-none"); } else { testCase.classList.add("scale-100", "border-none"); testCase.classList.remove("lg:scale-105", "border", "border-gray-200"); } }) if (!result.is_public) { document.getElementById("test-result").innerHTML = `

Hidden Test Case

` return; } document.getElementById("test-result").innerHTML = `
${codeResult ? atob(codeResult.stdin) : "No input available"}
${codeResult ? atob(codeResult.expected_output) : "No expected output available"}
${codeResult ? (codeResult.stderr || codeResult.compile_output ? atob(codeResult.stderr || codeResult.compile_output) : codeResult.stdout == null ? "" : atob(codeResult.stdout)) : "No output available"}
`; }); }); } else { batchOutputContainer.classList.add("hidden") outputContainer.classList.remove('hidden') output.textContent = codeResult.stderr ? atob(codeResult.stderr) : atob(codeResult.stdout || ''); } } catch (error) { console.error(error); } finally { loader.classList.add('hidden'); } } function getLanguageId8a4324e19cc34723ae4b9912a91f338d(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListeners8a4324e19cc34723ae4b9912a91f338d() { document .getElementById(`theme-toggle-8a4324e19cc34723ae4b9912a91f338d`) .addEventListener('click', toggleTheme8a4324e19cc34723ae4b9912a91f338d); document .getElementById(`run-code-8a4324e19cc34723ae4b9912a91f338d`) .addEventListener('click', runCode8a4324e19cc34723ae4b9912a91f338d); document .getElementById(`view-preview-8a4324e19cc34723ae4b9912a91f338d`) .addEventListener('click', switchToPreview8a4324e19cc34723ae4b9912a91f338d); }

Where script.js contains the JavaScript functionality. This approach keeps your HTML clean and promotes reusability of code across multiple pages.

Conclusion

By understanding these methods, you can effectively manage JavaScript in your web projects, ensuring better code quality and maintainability.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Method 1 – Inline JavaScript

Chapter 1 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

You can add JavaScript directly inside HTML tags using the onclick, onchange, or other event attributes. For example:

Explanation:
- When the user clicks the button, the JavaScript alert() function shows a popup with "Hello!".

Though this works, it's not recommended for larger projects because it mixes structure and behavior.

Detailed Explanation

Inline JavaScript allows developers to add functionality directly within HTML elements. In this case, clicking the button triggers a JavaScript function that displays a simple alert. This method, while straightforward, can complicate code management in larger applications since the structure (HTML) and behavior (JavaScript) are intertwined.

Examples & Analogies

Think of inline JavaScript like a chef constantly adding spices directly into a dish while cooking. While it might produce flavor, it can also lead to a chaotic kitchen where the recipe (structure) becomes hard to follow and manage.

Method 2 – Internal JavaScript

Chapter 2 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

You can include JavaScript inside the

Explanation:
- We select the button using its ID myButton.
- We assign an event handler to run when the button is clicked.
- The alert() function shows a message box.

Detailed Explanation

Internal JavaScript is written within the <script> tags in an HTML document. This method cleans up and organizes the code better than inline scripts. By using an ID to select the button, the script attaches a click event to it, resulting in a pop-up alert when clicked. It's useful because it keeps HTML and JavaScript separate yet within the same file.

Examples & Analogies

Using internal JavaScript is like having a well-organized recipe book where ingredients (HTML) and instructions (JavaScript) are kept together but clearly separated. This way, you can efficiently refer to it while cooking without mixing everything in one messy bowl.

Method 3 – External JavaScript

Chapter 3 of 3

πŸ”’ Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

For better organization, you can write JavaScript in a separate file:

index.html





External JavaScript Example


Hello JavaScript

script.js

document.getElementById("btn").addEventListener("click", function() {
alert("Button was clicked!");
});

Explanation:
- The JavaScript file is linked using the src attribute.
- We use addEventListener() to handle events (more flexible than using onclick).
This method keeps your HTML clean and makes it easier to manage larger scripts.

Detailed Explanation

External JavaScript files (with a .js extension) allow developers to separate JavaScript code from HTML entirely. Using the <script src="script.js"></script> tag, the HTML file links to a separate JavaScript file. This method improves maintainability and collaboration, as multiple HTML files can refer to the same script without duplication.

Examples & Analogies

External JavaScript is like having a communal library filled with different scripts rather than cramming all your books into one small shelf. Each library member (HTML document) can fetch the same book (JavaScript) whenever needed, making the collection easy to manage and update without clutter.

Key Concepts

  • Inline JavaScript: Embedding scripts directly within HTML elements.

  • Internal JavaScript: Placing JavaScript within <script> tags for better structure.

  • External JavaScript: Linking to separate files containing JavaScript code for reusability.

Examples & Applications

Inline: <button onclick="alert('Hello!')">Click Me</button> displays an alert when clicked.

Internal: <script>document.getElementById('myButton').onclick = function() { alert('You clicked the button!'); };</script> allows for structured event handling within HTML.

External: <script src='script.js'></script> links to a separate JavaScript file, improving code organization.

Memory Aids

Interactive tools to help you remember key concepts

🎡

Rhymes

Inline when it's quick, internal for a mix, external when you grow, keep your code in flow.

πŸ“–

Stories

Once, there was a tiny button who wanted to dance. Inline scripts made him move quickly, but as he grew, he learned internal dancing let him show his moves with style. Eventually, he united with external dancers, blending styles across the web!

🧠

Memory Tools

I-I-E: Inline, Internal, External. Remember the flow of including JavaScript in your code!

🎯

Acronyms

JIE

JavaScript Inclusion Examples - Inline

Internal

External.

Flash Cards

Glossary

Inline JavaScript

A method of adding JavaScript directly within HTML tags, using event attributes.

Internal JavaScript

JavaScript code placed within a <script> tag in the HTML document for better organization.

External JavaScript

JavaScript written in a separate file linked to an HTML document, promoting reusability and cleaner code.

Event Attributes

HTML attributes that specify JavaScript code to execute when a certain event occurs, such as onclick.

Document Object Model (DOM)

A programming interface that browsers implement to represent the structure of a webpage.

Reference links

Supplementary resources to enhance your learning experience.