JavaScript
JavaScript is the most popular programming language in the world, in part because it runs in a web browser, which is available on nearly every computer. While JavaScript's use extends beyond browsers, it's most frequently associated with creating dynamic interactions in a web page. When you think of interactive animations, content loading without a page refresh, or changes in the page's state (menus remaining opened or closed, for instance), it's most likely JavaScript working behind the scenes.
How to place JavaScript in HTML
Much like CSS, JavaScript can 1) be placed within an HTML document inline:
<button onclick="alert('Hello JavaScript!')">Trigger an alert</button>
2) within <script> tags:
<div id="demo"></div>
<script>
document.getElementById('demo').innerHTML = 'Hello JavaScript!';
</script>
and 3) as a separate document (again using <script>).
...
<script src="file.js"></script>
</body>
</html>
The last method is most preferrable, as it eliminates redundancy across multiple pages. While <script> can be placed in the <head>, you may often come across it at the bottom of the HTML page, as JavaScript needs the page to load before performing any changes. When using JS within a script tag, you typically want to include JavaScript code that waits for the document to load. Here's an example:
window.onload = function() {
// Do this once page has loaded
alert('Hello JavaScript!');
};
In-Class Examples
- Class Change with inline style change with JavaScript
See the Pen Change Color by Rich Hauck (@richhauck) on CodePen.
- Class Change using CSS
See the Pen Color Change 2 by Rich Hauck (@richhauck) on CodePen.
- Class Change with Window load listener
See the Pen Color Change with Window Event Listener by Rich Hauck (@richhauck) on CodePen.
- Class Change using JQuery
What is JQuery?
JQuery is an open source third party library that, at its core, is used to make querying HTML tags easier. By including JQuery in your page, you can select DOM elements using CSS selectors.
An extremely popular library for a long time, JQuery helped ensure JavaScript worked consistently across browsers. With the introduction of new features in JavaScript and emerging browser support, there's a good chance You Might Not Need JQuery (also see this CSS-Tricks article) for custom JavaScript.
In many cases where you seek interactive "plugins" for your pages (such as carousels, slideshows, tooltips, popups, etc.) JQuery will be required, as the respective author likely wrote their plugin with JQuery for broad support.