COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY

WEB SCIENCE | JAVASCRIPT PRINCIPLES

Topics from the International Baccalaureate (IB) 2014 Computer Science Guide. 
For Option C - Web Science, this section looks at Javascript principles
ALSO IN THIS SECTION
CREATING THE WEB PART 1
CREATING THE WEB PART 2​
SEARCHING THE WEB
DISTRIBUTED APPROACHES TO THE WEB
THE EVOLVING WEB
ANALYSING THE WEB
THE INTELLIGENT WEB

​NETWORK COMPONENTS
XML AND XMLT
PHP PRINCIPLES
JAVASCRIPT PRINCIPLES

REVISION CARDS
ANSWERS

Picture

JAVASCRIPT PRINCIPLES

KEY SYNTAX TERMINOLOGY
getElementById
  • Example: document.getElementById("demo")
  • Description: Selects and returns the element with the specified ID.

.innerHTML
  • Example: document.getElementById("demo").innerHTML = "Hello World!"
  • Description: Gets or sets the HTML content inside the selected element.

onclick
  • Example: <button onclick="alert('Hello!')">Click Me</button>
  • Description: An HTML attribute that executes JavaScript code when an element is clicked.

addEventListener
  • Example: element.addEventListener("click", function)
  • Description: Attaches an event handler to the specified element.

querySelector
  • Example: document.querySelector(".className")
  • Description: Returns the first element that matches a specified CSS selector.

querySelectorAll
  • Example: document.querySelectorAll("p")
  • Description: Returns all elements in the document that match a specified CSS selector.

createElement
  • Example: document.createElement("div")
  • Description: Creates a new HTML element.

appendChild
  • Example: parentElement.appendChild(childElement)
  • Description: Adds a new child element to a parent element.

removeChild
  • Example: parentElement.removeChild(childElement)
  • Description: Removes a child element from a parent element.

setAttribute
  • Example: element.setAttribute("id", "newId")
  • Description: Adds a new attribute to an HTML element or changes the value of an existing attribute.

getAttribute
Example: element.getAttribute("id")
Description: Returns the value of the specified attribute of an element.

style
  • Example: document.getElementById("demo").style.color = "blue"
  • Description: Gets or sets the inline style of an element.

function
  • Example: function myFunction() { /* code */ }
  • Description: Declares a function.

console.log
  • Example: console.log("Hello World!")
  • Description: Outputs a message to the web console.

Array.forEach
  • Example: array.forEach(function(element) { /* code */ })
  • Description: Executes a provided function once for each array element.

JSON.parse
  • Example: JSON.parse(jsonString)
  • Description: Parses a JSON string, constructing the JavaScript value or object described by the string.

JSON.stringify
  • Example: JSON.stringify(jsonObject)
  • Description: Converts a JavaScript object or value to a JSON string.

setTimeout
  • Example: setTimeout(function, milliseconds)
  • Description: Executes a function, after waiting a specified number of milliseconds.

fetch
  • Example: fetch('url')
  • Description: Used to make network requests to retrieve resources.

Promise
  • Example: new Promise(function(resolve, reject) { /* code */ })
  • Description: Represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
SECTION 1 | INTRODUCTION TO JAVASCRIPT
​JavaScript is a powerful and versatile programming language that plays a crucial role in modern web development. Unlike other programming languages that are typically used for server-side development, JavaScript primarily runs in the browser, making it an essential tool for creating interactive and dynamic web pages.

JavaScript in the Browser
JavaScript's primary role in web development is to enhance user experience by enabling interactivity on web pages. This includes a variety of functions such as:
  • Dynamic Content Updates | JavaScript allows content on a webpage to be updated dynamically without the need to reload the entire page. This is fundamental in creating responsive and interactive user interfaces.
  • Form Validation | Before submitting data to a server, JavaScript can validate user input on the client side, ensuring that the data is correct and complete.
  • Interactive Elements | Features like dropdown menus, modal windows, and carousels are often implemented using JavaScript, contributing to a rich and engaging user experience.
  • Animations | JavaScript can be used to create animations on web pages, adding visual appeal and enhancing the overall design.
SECTION 2 | JAVASCRIPT IN THE WEB ECOSYSTEM
JavaScript plays a pivotal role in the web ecosystem, interacting seamlessly with HTML and CSS while offering both client-side and server-side capabilities.

JavaScript and HTML - Creating Interactive Content
  • Manipulating the Document Object Model (DOM) | JavaScript interacts directly with the DOM, which is the structure that represents the HTML document. This interaction allows JavaScript to dynamically change content, structure, and style of web pages.
  • Event Handling | JavaScript responds to user interactions through events. Whether it’s clicking a button or submitting a form, JavaScript can capture these events and perform actions, making the web pages responsive and interactive.
  • JavaScript and CSS | Enhancing Web Design
  • Dynamic Styling: JavaScript can modify the CSS of HTML elements dynamically. This allows for real-time changes in style, like changing colors, fonts, or layouts based on user actions or other conditions.
  • Animations and Transitions | While CSS can handle simple animations and transitions, JavaScript can create more complex and interactive animations, offering a more engaging user experience.
  • Client-Side Scripting with JavaScript
  • Direct Interaction with Users | JavaScript runs directly in the user's browser, providing immediate feedback and interaction without the need to constantly communicate with the server. This results in faster and smoother user experiences.
  • Reduced Server Load | By handling many tasks on the client side, JavaScript reduces the workload on the server, which can be crucial for high-traffic websites.

Server-Side Scripting with JavaScript
  • Node.js and Beyond | The introduction of Node.js has enabled JavaScript to run on the server side. This means JavaScript can now be used to write server logic, including accessing databases, file systems, and handling HTTP requests and responses.
  • Full-Stack Development | With JavaScript's expansion to server-side scripting, it's possible to build entire web applications using just JavaScript, both on the client and server sides. This unification simplifies the development process and broadens the capabilities of JavaScript developers.

The integration of JavaScript with HTML and CSS forms the cornerstone of web development. Its ability to operate on both the client and server sides has made it an indispensable tool for modern web developers. 
Example Variable, IF statement, Loop, Array and Function

    
In this script
  • The gradeReport function takes an array of student grades.
  • It iterates over this array using a for loop.
  • Inside the loop, an if-else conditional structure is used to determine and log the grade of each student based on their score.
  • Each grade is determined by a range of scores (90 and above is an A, 80 to 89 is a B, etc.).
  • The function is then called with an example array grades, and it outputs the grade for each student in the console.
SECTION 3 | FUNCTIONS AND SCOPE
Functions are one of the fundamental building blocks in JavaScript, allowing you to define reusable blocks of code.

1. Function Declaration vs. Function Expression:
  • Function Declaration | Defines a function with the specified parameters. Example:
Function Declaration

    
  • Function Expression | Defines a function inside an expression. It can be named or anonymous and is typically assigned to a variable. Example:
Function Expression

    
SECTION 4 | BASIC EVENT HANDLING
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way.

Common web events include clicks, mouse movements, form submissions, and key presses.

Simple Event Listener Example
Event listeners are used to listen for and respond to events in the web page. Here is a basic example:
Event listeners

    
The above code explained

HTML Element
<button id="myButton">Click me!</button>: This is an HTML button element. It has an id attribute set to "myButton", which uniquely identifies this element in the document. The text inside the button element, "Click me!", is displayed as the button's label.

JavaScript Code Explanation
Selecting the Element
  • const button = document.getElementById("myButton");
  • This line of JavaScript code selects the HTML button element using its id. document.getElementById("myButton") is a method that finds and returns the element with the ID myButton.
  • The returned element is then stored in a constant variable named button.

Adding an Event Listener
  • button.addEventListener("click", function() { ... });
  • This line attaches an event listener to the button element.
  • .addEventListener is a method used to set up a function that will be called whenever the specified event ("click" in this case) is delivered to the target.

Event Type
  • "click"
  • This specifies the type of event to listen for. Here, it's listening for a click event, which is triggered when the user clicks on the button.

Callback Function
  • function() { alert("Button was clicked!"); }
  • This is a callback function that gets executed when the click event occurs on the button. It’s an anonymous function (a function without a name).
  • Inside this function, alert("Button was clicked!"); is called. This displays an alert box with the message "Button was clicked!" when the button is clicked.

The entire code block demonstrates how to respond to a user action (a button click) using JavaScript. When the user clicks the button with ID myButton, an alert box pops up displaying a message. This is a fundamental example of using JavaScript for interactive web page elements, a common practice in modern web development.
SECTION 5 | WORKING WITH DOCUMENT OJBECT MODEL (DOM)
The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. JavaScript can be used to manipulate the DOM, allowing dynamic changes to the web pages.

Introduction to the DOM
Document Object Model Basics | The DOM represents a web page as a tree of objects. Each HTML element is an object and can be accessed and manipulated using JavaScript. The DOM provides a representation of the document as a structured group of nodes and objects, which have properties and methods.

Selecting and Manipulating Elements
document.querySelector and document.querySelectorAll
  • document.querySelector | This method returns the first element that matches a specified CSS selector. For example, document.querySelector(".className") selects the first element with the class className.
  • document.querySelectorAll | Unlike querySelector, this method returns all elements matching the specified selector as a NodeList. For instance, document.querySelectorAll("p") selects all paragraph elements.

Changing Text and HTML Attributes
  • Changing Text | The textContent property can be used to get or set the text content of an element. For example, document.querySelector("h1").textContent = "New Heading"; changes the text of the first <h1> element.
  • Modifying HTML Attributes | JavaScript can change the attributes of HTML elements. For example, document.querySelector("img").src = "newimage.jpg"; changes the source of the first image element.

Event Handling in the DOM Practical Examples
Responding to a Click Event

    
This code selects a button with the ID myButton and sets up an event listener that shows an alert when the button is clicked.
Changing Element Style on Hover

    
Here, an element with the class box changes its background color to blue when the mouse hovers over it, and back to red when the mouse leaves.

​Understanding and manipulating the DOM is a key aspect of web development with JavaScript. It allows developers to create dynamic, responsive, and interactive web pages. By learning to select, manipulate, and handle events on DOM elements, developers can greatly enhance the user experience on web pages.
SAMPLE QUESTION | INTERACTIVE COLOUR CHANGE
​Bright Futures University has a webpage that allows students to change the background color of a paragraph based on their colour preference.

Consider the section of HTML and JavaScript code shown below. ​File name: colorChanger.html
​​File name: colourChanger.html

    
(a) (i) Describe the initial appearance of the colourChanger.html file when opened in a web browser. [2]

(ii) Explain the process that occurs when a user types “blue” into the text box and then clicks the "Change Colour" button. [2]
SAMPLE QUESTION | DYNAMIC WELCOME MESSAGE
​Dynamic Welcome Message
TechFuture Institute has a webpage that greets users with a personalized welcome message. The message changes based on the user's input.

Consider the section of HTML and JavaScript code shown below.

File name: welcomeMessage.html

    
​(a) (i) What is the initial state of the welcomeMessage.html page when it is first loaded in a web browser? [2]

(ii) Describe the sequence of events and processing that happens when a user enters the name "Alex" into the text box and clicks the "Greet Me" button. [3]
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.