Method 2 – Internal Javascript (2.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

Method 2 – Internal JavaScript

Method 2 – Internal JavaScript

Practice

Interactive Audio Lesson

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

Introduction to Internal JavaScript

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today we're going to learn about internal JavaScript. Who can tell me what they think internal JavaScript is?

Student 1
Student 1

Is it about putting JavaScript code in the HTML file?

Teacher
Teacher Instructor

Correct! We use the `<script>` tag to embed JavaScript within our HTML. This allows us to manipulate HTML content directly. For example, we can set up an event like a button click.

Student 2
Student 2

Can you show us what that looks like?

Teacher
Teacher Instructor

Absolutely! Here's a simple example: `<script> document.getElementById('myButton').onclick = function() { alert('You clicked the button!'); }; </script>`. This code will show an alert when the button is clicked.

Student 3
Student 3

So we’re adding behavior to our webpage?

Teacher
Teacher Instructor

Exactly! That's what makes JavaScript so powerful. Let’s summarize: Internal JavaScript lets us enhance interactivity by using the `<script>` tag to respond to user actions. Remember, it separates our script from our HTML content, keeping our files cleaner!

Using the Document Object Model (DOM)

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now that we know what internal JavaScript is, how does it connect with our webpage elements?

Student 4
Student 4

By using the DOM, right?

Teacher
Teacher Instructor

Right! The DOM represents our HTML documents as objects, and with JavaScript, we can manipulate these objects. For instance, we can change text or styles of elements.

Student 1
Student 1

Can we change a heading's text?

Teacher
Teacher Instructor

Yes! With a line like `document.getElementById('main-title').textContent = 'New Title';`, we directly change the content of that element. Can you think of why this is useful?

Student 2
Student 2

It makes the webpage dynamic!

Teacher
Teacher Instructor

Exactly! Summarizing, internal JavaScript interacts with the DOM, enabling real-time updates and interactivity on the webpage.

Event Handling

🔒 Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Let’s dive deeper into event handling. What happens when a user interacts with a webpage?

Student 3
Student 3

They might click a button or type in a field?

Teacher
Teacher Instructor

Exactly! With internal JavaScript, we can respond to these events. For example, the line `document.getElementById('myButton').onclick = function() { ... };` sets up a click event handler.

Student 4
Student 4

So, what would happen if we wanted to do something when the mouse hovers over an element?

Teacher
Teacher Instructor

Great question! We can use the `mouseover` event just like the `onclick` event to trigger changes when the mouse hovers over elements. Remember, handling events helps create interactive user experiences!

Student 1
Student 1

Can you summarize the events we've learned?

Teacher
Teacher Instructor

Sure! Internal JavaScript allows us to handle user interactions, using events like clicks or mouse movements to trigger responses, enhancing the interactivity of our webpages.

Introduction & Overview

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

Quick Overview

Internal JavaScript allows developers to embed JavaScript code directly within HTML using the

Detailed

Method 2 – Internal JavaScript

In this section, we dive into the use of internal JavaScript, a method of incorporating JavaScript code directly into an HTML file using the <script> tag. Unlike inline JavaScript, which intertwines HTML attributes with scripts, internal JavaScript maintains a clearer separation between content structure and behavior.

Key Points Covered:

  1. Structure of Internal JavaScript:
  2. You can include JavaScript in your HTML document by embedding it within <script> tags right before the closing <body> tag for effective loading. An example structure is:
Code Editor - html
`, -1); codePreview23acdb8ec0a94b95be608d508aa743bb.setTheme('ace/theme/textmate'); // Attach try it yourself button listener document.getElementById(`try-it-23acdb8ec0a94b95be608d508aa743bb`).addEventListener('click', () => { switchToEditor23acdb8ec0a94b95be608d508aa743bb(); }); function switchToEditor23acdb8ec0a94b95be608d508aa743bb() { // Initialize the editor editor23acdb8ec0a94b95be608d508aa743bb = ace.edit("23acdb8ec0a94b95be608d508aa743bb") setLanguage23acdb8ec0a94b95be608d508aa743bb(language23acdb8ec0a94b95be608d508aa743bb); editor23acdb8ec0a94b95be608d508aa743bb.setValue(` My First JavaScript Page

Welcome to JavaScript!

`, -1); initEditorSettings23acdb8ec0a94b95be608d508aa743bb(); attachEventListeners23acdb8ec0a94b95be608d508aa743bb(); document.getElementById(`editor-container-23acdb8ec0a94b95be608d508aa743bb`).classList.remove('hidden'); document.getElementById(`preview-container-23acdb8ec0a94b95be608d508aa743bb`).classList.add('hidden'); } function switchToPreview23acdb8ec0a94b95be608d508aa743bb() { // Clean up the editor instance editor23acdb8ec0a94b95be608d508aa743bb.destroy(); editor23acdb8ec0a94b95be608d508aa743bb = null; document.getElementById(`editor-container-23acdb8ec0a94b95be608d508aa743bb`).classList.add('hidden'); document.getElementById(`preview-container-23acdb8ec0a94b95be608d508aa743bb`).classList.remove('hidden'); // Reattach the try it yourself button listener document.getElementById(`try-it-23acdb8ec0a94b95be608d508aa743bb`).addEventListener('click', () => { switchToEditor23acdb8ec0a94b95be608d508aa743bb(); }); } function initEditorSettings23acdb8ec0a94b95be608d508aa743bb() { editor23acdb8ec0a94b95be608d508aa743bb.setOptions({ enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true, }); editor23acdb8ec0a94b95be608d508aa743bb.setTheme('ace/theme/xcode'); editor23acdb8ec0a94b95be608d508aa743bb.session.setMode(`ace/mode/${language23acdb8ec0a94b95be608d508aa743bb}`); } function setLanguage23acdb8ec0a94b95be608d508aa743bb(lang) { language23acdb8ec0a94b95be608d508aa743bb = lang; editor23acdb8ec0a94b95be608d508aa743bb.session.setMode(`ace/mode/${lang}`); } // Add method to update code programmatically function setCode23acdb8ec0a94b95be608d508aa743bb(code) { editor23acdb8ec0a94b95be608d508aa743bb.setValue(code, -1); } function toggleTheme23acdb8ec0a94b95be608d508aa743bb() { const isDarkMode = editor23acdb8ec0a94b95be608d508aa743bb.getTheme() === 'ace/theme/monokai'; const sunIcon = document.getElementById(`theme-icon-23acdb8ec0a94b95be608d508aa743bb`); const moonIcon = document.getElementById(`moon-icon-23acdb8ec0a94b95be608d508aa743bb`); if (isDarkMode) { editor23acdb8ec0a94b95be608d508aa743bb.setTheme('ace/theme/xcode'); sunIcon.classList.remove('hidden'); moonIcon.classList.add('hidden'); } else { editor23acdb8ec0a94b95be608d508aa743bb.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 runCode23acdb8ec0a94b95be608d508aa743bb() { const code = btoa(editor23acdb8ec0a94b95be608d508aa743bb.getValue()); const stdIn = btoa(document.getElementById("input-23acdb8ec0a94b95be608d508aa743bb").value); const loader = document.getElementById(`run-loader-23acdb8ec0a94b95be608d508aa743bb`); const output = document.getElementById(`output-23acdb8ec0a94b95be608d508aa743bb`); const outputContainer = document.getElementById(`run-output-23acdb8ec0a94b95be608d508aa743bb`); const batchOutputContainer = document.getElementById(`batch-run-output-23acdb8ec0a94b95be608d508aa743bb`); 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: language23acdb8ec0a94b95be608d508aa743bb, language_id: getLanguageId23acdb8ec0a94b95be608d508aa743bb(language23acdb8ec0a94b95be608d508aa743bb), 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 getLanguageId23acdb8ec0a94b95be608d508aa743bb(language) { const languages = { javascript: 63, python: 71, java: 62, c_cpp: 49, }; return languages[language]; } function attachEventListeners23acdb8ec0a94b95be608d508aa743bb() { document .getElementById(`theme-toggle-23acdb8ec0a94b95be608d508aa743bb`) .addEventListener('click', toggleTheme23acdb8ec0a94b95be608d508aa743bb); document .getElementById(`run-code-23acdb8ec0a94b95be608d508aa743bb`) .addEventListener('click', runCode23acdb8ec0a94b95be608d508aa743bb); document .getElementById(`view-preview-23acdb8ec0a94b95be608d508aa743bb`) .addEventListener('click', switchToPreview23acdb8ec0a94b95be608d508aa743bb); }
  1. Interactivity through DOM:
  2. Internal JavaScript allows you to manipulate the Document Object Model (DOM), enabling developers to configure user interactions effectively. Here, an onclick event handler directly responds when users click a button, demonstrating the power of event handling in JavaScript.
  3. Comparison with Other Methods:
  4. Inline JavaScript mixes behavior with structure, making it harder to manage as projects grow. In contrast, internal scripting offers better organization and readability within the HTML file.
  5. Future methods, like external JavaScript, are also introduced, wherein developers can keep JavaScript in a separate file and link to it, promoting even better management of scripts.

In conclusion, using internal JavaScript enhances web interactivity effectively while keeping the code structured and easier to maintain, laying the groundwork for more advanced JavaScript methodologies in future sections.

Audio Book

Dive deep into the subject with an immersive audiobook experience.

Including JavaScript Using the `<script>` Tag

Chapter 1 of 2

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

You can include JavaScript inside the

Detailed Explanation

In this chunk, we learn how to include JavaScript within a webpage using the <script> tag. This method allows you to write JavaScript directly in the HTML document. When the webpage is loaded, the JavaScript code inside the <script> tag is executed by the browser. The example shows a button that, when clicked, triggers a JavaScript function to display an alert box telling the user that they clicked the button. This method is useful for quick scripts that interact closely with the HTML elements on the page.

Examples & Analogies

Think of the <script> tag like a recipe card attached to your cookbook (the HTML document) with specific instructions on what to do when a guest (the user) interacts with the meal (the webpage). When the guest clicks the button (the meal), they get a delightful surprise that enhances their experience.

Selecting HTML Elements Using JavaScript

Chapter 2 of 2

🔒 Unlock Audio Chapter

Sign up and enroll to access the full audio experience

0:00
--:--

Chapter Content

● 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

Here, we delve into how JavaScript interacts with HTML elements. The document.getElementById("myButton") method is used to select the HTML element (the button in this case) by its unique ID ('myButton'). Then, an event handler is assigned to this button, which defines what happens when the button is clicked. The onclick property holds a function that calls alert(), which displays a message to the user. This process illustrates how JavaScript can make a webpage more interactive by responding to user actions.

Examples & Analogies

Imagine you have a remote control for a TV (the button). When you press a button on the remote (click), it sends a signal to the TV (via JavaScript) to change the channel (show a message). The ID of the button ensures that we're telling the right remote (button) to perform the action.

Key Concepts

  • Internal JavaScript: Use of <script> tags in HTML to include JavaScript.

  • Document Object Model (DOM): Represents HTML document structure, enabling manipulation via JavaScript.

  • Event Handling: JavaScript responds to events like clicks and keypresses to enhance interactivity.

Examples & Applications

Example of internal JavaScript usage:

document.getElementById('myButton').onclick = function() {

alert('You clicked the button!');

};

Changing an element's content through JavaScript:

document.getElementById('heading').textContent = 'New Heading';

Memory Aids

Interactive tools to help you remember key concepts

🎵

Rhymes

In the script, the code shall sit,

📖

Stories

Imagine a magician (JavaScript) performing tricks (interactivity) on stage (webpage) to amaze the audience (users). They pull rabbits (dynamic content) from hats.

🧠

Memory Tools

DOM: "Dancing On My webpage" - to remember how JavaScript can manipulate webpage elements dynamically.

🎯

Acronyms

ICE

Internal Code Enhancer - reminding you that internal JavaScript enhances interactivity.

Flash Cards

Glossary

Internal JavaScript

JavaScript code that is embedded directly within an HTML document using the <script> tag.

Document Object Model (DOM)

A programming interface that represents the structure of a webpage, allowing JavaScript to manipulate HTML elements.

Event Handling

The process of executing specific JavaScript code in response to user actions on the webpage.

Reference links

Supplementary resources to enhance your learning experience.