Introduction to JavaScript

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

JavaScript interacts with HTML through the DOM. What capability does this provide to web developers?

  • Executing complex database queries from the client-side.
  • Rendering 3D graphics using only HTML and CSS.
  • Directly manipulating server-side code without the need for server requests.
  • Dynamically modifying web page content and styles within the browser. (correct)

When including JavaScript in a web page, what benefit does linking to an external .js file provide over embedding the code directly within <script> tags?

  • It automatically applies the JavaScript to all HTML files in the same directory.
  • External files execute faster because browsers prioritize their loading.
  • Embedded code cannot be cached due to security restrictions.
  • It facilitates code reuse across multiple pages and can improve page load times through browser caching. (correct)

Different web browsers use different JavaScript engines. What implications does this have for web developers?

  • Developers must write separate code versions for each major browser engine.
  • JavaScript code will only run on the browser it was initially written for.
  • JavaScript offers seamless cross-browser compatibility, as each JavaScript engine ensures code runs the same way.
  • While the core JavaScript language remains consistent, minor differences in engine implementations may require developers to test across multiple browsers. (correct)

What is the primary distinction between client-side scripting (like JavaScript) and server-side scripting?

<p>Client-side scripts are processed in the user's browser, whereas server-side scripts are processed on the web server. (A)</p> Signup and view all the answers

Consider the following JavaScript code snippet: document.getElementById('myHeading').textContent = 'Hello World!'; What does this code accomplish?

<p>It finds the HTML element with the ID 'myHeading' and changes its text to 'Hello World!' (B)</p> Signup and view all the answers

Flashcards

What is JavaScript?

A programming language mostly used to define the interactive behavior of web pages. It was invented by Brendan Eich.

Embedding JavaScript

Embedding the JavaScript code between a pair of <script> and </script> tags.

Inline JavaScript

Placing the JavaScript code directly inside an HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc.

External JavaScript

Creating an external JavaScript file with the .js extension and then load it within the page through the src attribute of the <script> tag.

Signup and view all the flashcards

Advantages of external JS

It separates HTML and code, makes HTML and JS easier to read, and cached JS files can speed up page loads.

Signup and view all the flashcards

Study Notes

Introduction to JavaScript

  • JavaScript defines the interactive behavior of webpages.
  • Brendan Eich invented it.
  • JavaScript allows manipulation of webpage content and styling in a browser.
  • Along with HTML and CSS, it forms the foundation of web browsers and the internet.
  • JavaScript is considered one of the most popular programming languages.
  • Many open-source mapping and data visualization libraries are written in JavaScript, including Leaflet, MapLibre GL JS, OpenLayers and D3.
  • Commercial web mapping services provide JavaScript APIs for building web maps, such as Google Maps JavaScript API, Mapbox GL JS, and ArcGIS API for JavaScript.

JavaScript Basics

  • JavaScript was initially created to make webpages alive.
  • Programs are called scripts, written in HTML, and run automatically as the page loads.
  • JavaScript can execute in the browser, on the server, or on any device with a JavaScript engine.
  • Browsers have built-in engines, sometimes called "JavaScript virtual machines".
  • Different engines have different codenames.
    • Chrome, Opera, and Edge use V8.
    • Firefox uses SpiderMonkey.
  • JavaScript advantages include integration with HTML/CSS, simplicity, and default support in major browsers.
  • JavaScript is a browser technology that combines HTML, CSS, and programming capabilities.
  • It also enables the creation of servers and mobile applications.

Examples of JavaScript's Capabilities

  • JavaScript can change HTML content.
    • Using the getElementById() method, elements can be found and their content altered.
    • For example, document.getElementById("demo").innerHTML = "Hello JavaScript"; changes an element's content to "Hello JavaScript".
    • The innerHTML property retrieves or sets the HTML markup within an element.
  • JavaScript is able to change HTML style attributes using CSS.
    • For example, document.getElementById("demo").style.fontSize = "35px"; changes the font size of an element.
  • Can hide HTML elements.
    • For example, document.getElementById("demo").style.display = "none"; hides an element.
  • Can show hidden HTML elements.
    • For example, document.getElementById("demo").style.display = "block"; shows an element by modifying the display style.

How to Create JavaScript Files

  • Create a new folder named "scripts".
  • Inside the "scripts" folder, create a new text document called main.js.
  • In your index.html file, add <script src="scripts/main.js"></script> just before the closing </body> tag to link the JavaScript file.
    • This applies the JavaScript to the page similar to CSS.
  • Add const myHeading = document.querySelector('h1'); to the main.js file.
  • Also add myHeading.textContent = "Hello world!''; to the main.js file.
  • Ensure the HTML and JavaScript files are saved before loading the index.html file in the browser.
  • querySelector() grabs a reference to the heading.
    • Used to select an element before manipulating it, similar to CSS selectors.
  • Use textContent property of the myHeading variable to set the content of the heading to "Hello world!".

Adding JavaScript to Web Pages

  • Embedding the JavaScript code between <script> and </script> tags.
  • Creating an external JavaScript file with the .js extension and loading it within the page through the src attribute of the <script> tag.
  • Placing the JavaScript code directly inside an HTML tag using special tag attributes such as onclick, onmouseover, onkeypress, or onload.

Embedding JavaScript Code

  • JavaScript code can be directly embedded within web pages by placing it between <script> and </script> tags.
  • The <script> tag indicates that the content should be interpreted as executable script and not HTML.

Calling an External JavaScript File

  • JavaScript code can also be placed in a separate file with a .js extension and referenced in the HTML document using the src attribute of the <script> tag.
  • For example: <script src="js/hello.js"></script>.
  • This is useful for making the same scripts available to multiple documents, reducing redundancy and simplifying website maintenance.
  • Steps:
    • Create a JavaScript file named hello.js and add JavaScript code.
    • Call the external JavaScript file within a web page using the <script> tag, specifying the file path in the src attribute like in <!DOCTYPE html>...<script src="js/hello.js"></script>...</html>.
  • When you save the JavaScript code with a .js extension.
  • External scripts are practical when the same code is used in many different web pages.
  • JavaScript files have the .js extension.
  • You can place an external script reference in <head> or <body>.
  • The script behaves as if it was located where the <script> tag is located.
  • External scripts cannot contain <script> tags.

Advantages of External JavaScript Files

  • Separates HTML and JavaScript code.
  • Makes HTML and JavaScript easier to read and maintain.
  • Cached JavaScript files can speed up page loads.
  • Several script files can be added to one page by using multiple script tags.

External References

  • An external script can be referenced in three ways:
    • With a full URL (a full web address).
    • With a file path (like /js/).
    • Without any path.
  • This example shows using a full URL to link to myScript.js.
    • <script src="https://www........com/js/myScript.js"></script>

Placing JavaScript Code Inline

  • JavaScript code can be placed inline directly inside HTML tags using attributes such as onclick, onmouseover, onkeypress, and onload.
  • One should avoid placing large amounts of JavaScript code inline, as it can clutter the HTML and make the code difficult to maintain.

Positioning Scripts in HTML Documents

  • The <script> element can be placed in the <head> or <body> section of an HTML document.
  • Ideally, scripts should be placed at the end of the body section, just before the closing </body> tag.
    • It will make webpages load faster.
    • It prevents obstruction of initial page rendering.
  • Each <script> tag blocks the page rendering process until it fully downloads and executes the JavaScript code.
    • Placing scripts in the head section can negatively impact website performance.

JavaScript <head>

  • JavaScript function is placed in the <head> section of an HTML page.
  • The function is invoked (called) when a button is clicked.

JavaScript <body>

  • JavaScript function is placed in the <body> section of an HTML page.
  • The function is called when a button is clicked.

Client-Side vs. Server-Side Scripting

  • Client-side scripting languages such as JavaScript and VBScript are interpreted and executed by the web browser.
  • Server-side scripting languages such as PHP, ASP, Java, Python, and Ruby run on the web server and send output back to the web browser in HTML format.
  • Client-side scripting offers advantages over traditional server-side scripting.
  • You can use JavaScript to check if the user has entered invalid data to prevent unnessecary data validation to the server.
  • Response from a server-side script is slower than client-side scripts because server-side scripts areprocessed on a remote computer.

JavaScript Display Possibilities

  • JavaScript can "display" data in different ways:
    • Writing into an HTML element, using innerHTML.
    • Writing into the HTML output using document.write().
    • Writing into an alert box, using window.alert().
    • Writing into the browser console, using console.log()

Simple Slideshow Creation

  • Slideshow creation involves a container for the slides.
  • Base Styles Tasks:
    • Set container for slides
    • Position slides one above the other inside a container
    • Define how slides appear and disappear
    • Smoothly change transparency for fading and fading effect
  • Always change classes and IDs so that there are no conflicts with your sites.

CSS

  • CSS Styles
    • position: relative
    • height: 300px
    • padding: 0px
    • margin: 0px
    • list-style-type: none
  • CSS Slide
    • position: absolute
    • left: 0px
    • top: 0px
    • width: 100%
    • height: 100%
    • opacity: 0
    • z-index: 1 --webkit-transition: opacity 1s --moz-transition: opacity 1s --o-transition: opacity 1s -transition: opacity 1s
  • CSS Showing
    • opacity: 1
    • z-index: 2
  • Code to the appearance of a slideshow
    • font-size: 40px
    • padding: 40px
    • box-sizing: border-box
    • background: #333
    • color: #fff
  • Styles for a slideshow should always be different colors like red, orange, green, blue and purple.

JavaScript Slideshow

  • JavaScript hides the current slide and shows the next one by changing the names of the slide classes.
  • var slides = document.querySelectorAll('#slides .slide');
  • var currentSlide = 0;
  • var slideInterval = setInterval(nextSlide, 2000);
  • Class names for slides should be like .slide and .slide showing.
  • querySelectorAll gets all the slides from the container (The querySelectorAll() Document method returns a static (not dynamic) NodeList containing all found document elements that match the specified selector).
  • A variable saves the slideshow index.
  • At the end, we set an interval of two seconds for the next slide (2000ms).
  • In our case, 5 slides. Let's count all the numbers: 1%5=1, 2%5=2, 3%5=3,4%5=4, and 5%5=0.
  • After getting the index of the slide, we change the class and show the new one. Again, transparency is handled by the transition property.

Add Controls to the Slider

  • Time to add a pause button, next slide and previous slide.
  • Pause Button.
    • First, add the button to the HTML:
    • The code should be like. <button class="controls" id="pause">Pause</button>
  • Add the Javascript code:
    • Add a variable to store when the slider is active.
    • The code should be like var playing = true;
    • Add a variable so that we don't have to search for it later in the document.
    • The code should be like var pauseButton = document.getElementById('pause');
    • The pauseslideshow funtion stops the slider and writes "Play" to the pause button.
    • Example pauseButton.innerHTML = 'Play';
    • Start the slider and sets Pause to the Play button. The code should be like this pauseButton.innerHTML = 'Pause';
  • Play/Pause button can pause the slider and start it.

Next and Previous Buttons

  • HTML code: <button class="controls" id="previous">Previous</button> and <button class="controls" id="next">Next</button>.
  • Javascript code example (currentSlide+1)%slides.length;.
  • The currentslide variables must be calculated.

Document Object Model (DOM)

  • Every family tree has a head, and for the DOM tree, the head is the html element that starts out the web page.
  • The head and body elements in the HTML code are called child objects of the html object in the DOM tree.
  • In DOM terminology these individual parts of the document are known as nodes.
  • With the HTML DOM, use JavaScript to build HTML documents, navigate their hierarchical structure, and add, modify, or delete elements and attributes or their content.
  • Almost anything found in an HTML document can be accessed, changed, deleted, or added using the JavaScript with the help of HTML DOM.
  • The browser receives an HTML document and creates a model of the page.
  • The browser displays the page on screen.

JavaScript and the Document Object Model

  • The standardization of the DOM was handled by the World Wide Web Consortium (W3C), which last developed a recommendation in 2004.
  • In HTML DOM (Document Object Model), every element is a node.
    • A document is a document node.
    • All HTML elements are element nodes.
    • All HTML attributes are attribute nodes.
    • Text inserted into HTML elements are text nodes.
    • Comments are comment nodes.
  • The DOM is sometimes referred to as an Application Programming Interface (API) for accessing HTML documents with JavaScript.
  • You can also call JavaScript files external to the HTML document to assist JavaScript with HTML DOM.
  • The browser creates the DOM that resides in the document variable and triggers a DOMContentLoaded event.
  • The principal standardization of DOM was handled by the W3C principal W3C standardization of the DOM - standardization of DOM was handled by the World Wide Web Consortium (W3C), which last developed a recommendation in 2004.
  • W3C now publishes stable snapshot of the WHATWG standard - the W3C now publishes stable snapshots of the WHATWG standard
  • HTML DOM element as node - in HTML DOM (Document Object Model), every element is a node
  • Type of element as node - a document is a document node; all HTML elements are element nodes; all HTML attributes are attribute nodes; text inserted into HTML elements are text nodes; comments are comment nodes
  • Elements in the DOM tree = JavaScript objects - just like that DOM tree, JavaScript treats each element contained in a web page a s an object
  • JavaScript Object Feature = Properties - Properties define information about object.
  • JavaScript Object Feature = Methods - Methods are actions to take with the objects.
  • the browser uses the DOM tree to maintain elements, content, styles in an HTML5 webpage
  • browsers grants JavaScript programs full access to the DOM tree, which allows them to control webpages
  • JavaScript programs can interact with all objects on the web page via the .js code and .css files.

How DOM Works

  • The browser creates a DOM based on the HTML, then renders it to the user
  • When the user fills out a form, DOM takes their input
  • DOM changes and user sees the updated page when the form is filled out

Document Properties

  • activeElement: Returns the currently focused element
  • anchors: Returns a list of all anchor elements.
  • body: Sets or returns the <body> element
  • cookie: Returns all cookie names and values.
  • characterSet: Returns the character set defined in the document.
  • documentElement: Returns the DOM object for the <html> element
  • documentMode: Returns the mode used by the browser to display
  • domain: Returns the domain name of the server
  • head: Returns the head element.
  • URL: Returns the full URL for the web page.

Document Methods

  • createElement(): Adds a new element object
  • createTextNode(): Adds a new text object
  • getElementbyId(id): Returns an element object with the specified id value
  • getElementsByClass Name(class): all of the elements that have that class
  • getElementsByTagname(tag). Returns list of these has Attribute()
  • Returns if the object has any attribute with tag name returns true or false
  • write(text): Sends the specified text to the web page

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

JavaScript Basics for Web Development
5 questions
JavaScript in Web Development
12 questions
Use Quizgecko on...
Browser
Browser