Introduction to JavaScript

How JavaScript adds behavior and interactivity to web pages

What Is JavaScript?

JavaScript is a programming language that allows web pages to respond to user actions and change what appears on the screen. It is commonly used for interactive menus, form validation, image galleries, and content that updates without loading an entirely new page.

JavaScript works alongside HTML, which structures the content, and CSS, which controls its appearance. Each has a different role in creating a complete website.

How JavaScript Works in a Browser

Web browsers include a JavaScript engine that executes scripts. A script can read information from a page, perform calculations, respond to events, and update elements in the document.

For example, when someone selects a button, JavaScript can respond to the click by displaying a message or showing hidden content. It can also check the information entered into a form before that information is submitted.

How JavaScript Works with HTML and CSS

HTML provides elements such as buttons, links, headings, and forms. CSS determines how those elements look. JavaScript can interact with the elements and change their content, attributes, or classes.

This example website uses all three technologies for its mobile navigation. HTML defines the menu and its button, CSS controls their layout and visibility, and JavaScript opens or closes the menu when the button is selected.

Responding to Events

An event is something that happens in the browser, such as a click, a key press, or a form submission. JavaScript can listen for events and run code in response.

For example, the mobile menu button on this website responds to a click. Its script updates the menu's visible state and the button's aria-expanded attribute so the interface communicates whether the menu is open.

The Document Object Model

The Document Object Model, usually called the DOM, represents the HTML document as a collection of objects that scripts can access. JavaScript can use the DOM to find an element, read its text, change an attribute, or add and remove content.

On this site, JavaScript finds the element used to display the copyright year and inserts the current year. This avoids having to edit the year manually each January.

Using External JavaScript Files

JavaScript can be included directly in an HTML document or stored in a separate file. External scripts help keep page content separate from behavior and allow the same code to be used across multiple pages.

This website uses /js/navigation.js for the responsive navigation menu and /js/current-year.js for the footer year. Both files are hosted on this example domain and linked from the HTML pages.

Continue Exploring Web Development

JavaScript makes websites interactive, while HTML and CSS provide their structure and appearance. For more detailed lessons and examples, return to the main tutorial website.

Explore HTML Tutorials