info1300-2024sp-documents

Project 3: Interactivity JavaScript Snippets

The following snippets use jQuery for basic website interactivity.

Feel free to copy and paste all snippets in this document. No citation required.

To use these snippets, you must load jQuery before your JavaScript script (e.g. cookie-banner.js) at the very end of the <body> element:

  <script src="scripts/jquery-3.7.1.js"></script>
  <script src="scripts/TODO_NAME_OF_JAVASCRIPT_FILE.js"></script>
</body>

Table of Contents

Accessing an Element in a Snippet

$("TODO_CSS_SELECTOR")

Replace TODO_CSS_SELECTOR with any CSS selector. Any CSS selector will do (example: nav > ul > li).

Note: If the selector covers more than 1 element, this snippet will return all elements described the selector.

Access Element by id= Example

If you want to find a specific element by its id= attribute, use the ID selector. (Remember, id= must be unique.)

HTML:

<div id="example">

JavaScript:

$("#example")

Access Elements by class= Example

If you want to find elements by their class= attributes, use the class selector.

HTML:

<img class="slide" id="slide1" src="images/slide1.jpg" alt="Slide 1">
<img class="slide" id="slide2" src="images/slide2.jpg" alt="Slide 2">
<img class="slide" id="slide3" src="images/slide3.jpg" alt="Slide 3">

JavaScript:

$(".slide")

This will return elements id="slide1", id="slide2", and id="slide3".

Access Element(s) by CSS Selector Example

Let’s say that I only want to access the elements of class slide that are direct children of a <div id="slides">. Let’s use the child combinator selector.

HTML:

<div class="slides">
  <img class="slide" id="slide1" src="images/slide1.jpg" alt="Slide 1">
  <img class="slide" id="slide2" src="images/slide2.jpg" alt="Slide 2">
  <img class="slide" id="slide3" src="images/slide3.jpg" alt="Slide 3">
</div>

<img class="slide" id="slide4" src="images/slide4.jpg" alt="Slide 4">

JavaScript:

$(".slides > .slide")

This will return elements id="slide1", id="slide2", and id="slide3".

Event Snippets

Event snippets let you react to an event that occurs on an element. For example, a user clicks on an element.

Use Snippets that Go Inside Event Snippets to add/remove CSS classes, check the screen width, or toggle a CSS class in response to an event.

jQuery supports several events. This includes mouse (e.g. click, right click, double click, hover, etc.), keyboard (e.g. key press, etc.), and browser (e.g. scroll, resize window) events.

Note: Each event snippet includes an access element(s) snippet.

On-Click Element Event Snippet & Example

When a user clicks on element.

$("TODO_CSS_SELECTOR").click(function() {
  // TODO: snippet(s) to respond to the click event.
});

Example:

<button id="cookie-accept-button">Accept</button>
$("#cookie-accept-button").click(function() {
  // TODO: hide cookie banner
});

On-Page-Loaded Event Snippet

Once the page has loaded, the ready event will trigger. This event is useful to setting timers or initializing state.

Tip: This snippet can be useful for changing part of a page based on the time of day or day of week.

$(document).ready(function() {
  // TODO: snippet(s) to respond to the ready event.
});

On-Window-Resize Event Snippet

In some situations, you may want to respond when the user resizes the browser window.

Tip: When using hamburger menus the navigation menu is often hidden until the user clicks the hamburger menu. If the navigation menu is hidden and the user resizes their browser window, you may want to remove the hamburger menu, and show a navigation bar.

Replace TODO_SCREEN_WIDTH with a screen width like 500.

$(window).resize(function() {
  if ($(document).width() < TODO_SCREEN_WIDTH) {
    // TODO: snippet(s) to respond when the screen size is less than TODO_SCREEN_WIDTH
  } else {
    // TODO: snippet(s) to respond when the screen size greater than or equal to the TODO_SCREEN_WIDTH
  }
});

On-Hover Element Event Snippet

When a user hovers with their mouse over an element.

Note: You will often find that using the CSS :hover pseudo-class selector is easier in most cases.

$("TODO_CSS_SELECTOR").hover(function() {
  // TODO: snippet(s) to respond to when the mouse enters the element.
}, function() {
  // TODO: snippet(s) to respond to when the mouse leaves the element.
});

Timer (every n seconds) Event Snippet & Example

If you want to do something every n seconds, you can set a timer “event”.

  1. Place the timer event snippet inside the ready event snippet.
  2. Replace TODO_TIME_MILLISECONDS with the m milliseconds you want to pass before triggering the event. 1000 × n seconds = m milliseconds.
setInterval(function() {
  // TODO: snippet(s) to respond to when TODO_TIME_MILLISECONDS has passed.
}, TODO_TIME_MILLISECONDS);

This snippet is useful to auto advance a carousel or a slideshow; every 10 seconds, go to the next slide.

setInterval(function() {
  // TODO: show next slide.
}, 10000);

Snippets That Go Inside Event Snippets

All of these snippets may be used any where there is a TODO in an event snippet.

Add/Remove CSS Class Snippets & Examples

These snippets let you add and remove CSS classes to elements.

Tip: For some CSS properties you may need to add the !important to force the browser to make the toggle change.

Note: Each Add/Remove CSS Class snippet includes an access element(s) snippet.

Add CSS Class to Element Snippet

This snippet will add a CSS class to an element.

$("TODO_CSS_SELECTOR").addClass("TODO_CSS_CLASS_NAME");

Replace TODO_CSS_CLASS_NAME with a CSS class name (omit the .).

Remove CSS Class from Element Snippet

This snippet will remove a CSS class from an element.

$("TODO_CSS_SELECTOR").removeClass("TODO_CSS_CLASS_NAME");

Replace TODO_CSS_CLASS_NAME with a CSS class name (omit the .).

CSS Class Show/Hide Snippet Example

Let’s say you want to show #slide2 and also hide #slide1 and #slide3.

HTML:

<img class="slide" id="slide1" src="images/slide1.jpg" alt="Slide 1">
<img class="slide hidden" id="slide2" src="images/slide2.jpg" alt="Slide 2">
<img class="slide hidden" id="slide3" src="images/slide3.jpg" alt="Slide 3">

CSS:

.hidden {
  display: none;
}

Hide all elements and show #slide2.

$(".slide").addClass("hidden");
$("#slide2").removeClass('hidden');

Screen Width Snippet & Example

Use this snippet inside of an event snippet.

In some situations, you may want add/remove classes based on the screen width.

Replace TODO_SCREEN_WIDTH with a screen width like 500.

if ($(document).width() < TODO_SCREEN_WIDTH) {
  // TODO: snippet(s) to respond when the screen size is less than TODO_SCREEN_WIDTH
} else {
  // TODO: snippet(s) to respond when the screen size greater than or equal to the TODO_SCREEN_WIDTH
}

Screen Width Snippet Example

When the browser loads a page, this example will add/remove classes to initialize the element based on the browser window’s width. If the browser’s width is greater than (or equal to) 500 pixels, the active class is added to the element, setting it to the color red.

<div id="width-element">
  When the "Toggle" button is clicked, the background color will toggle between blue and red.
</div>
#width-element {
  background-color: blue;
}

.active {
  background-color: red !important;
}
$(document).ready(function() {
  if ($(document).width() < 500) {
    $("#width-element").removeClass("active");
  } else {
    $("#width-element").addClass("active");
  }
});

Toggle / Conditional Snippets & Example

Use this snippet inside of an event snippet.

Sometimes you want one thing to happen when you click a button and then something else to happen when you click the button again. Or sometimes you want something to happen, if an element has a particular CSS class on it.

Tip: Toggle/Conditional snippets are useful for hamburger menus. If the navigation menu/bar is visible (no hidden class), then hide it.

Replace TODO_TOGGLE_ELEMENT with a CSS selector that selects the HTML element you want to toggle some CSS class on: TODO_TOGGLE_CSS_CLASS.

if ($("TODO_TOGGLE_ELEMENT").hasClass("TODO_TOGGLE_CSS_CLASS")) {
  // TODO: snippet(s) for when TODO_TOGGLE_CSS_CLASS IS on the TODO_TOGGLE_ELEMENT.
} else {
  // TODO: snippet(s) for when TODO_TOGGLE_CSS_CLASS is NOT on the TODO_TOGGLE_ELEMENT.
}

Toggle Snippet Example

<button id="toggle-button">Toggle Red/Blue</button>
<div id="toggle-element">
  When the "Toggle" button is clicked, the background color will toggle between blue and red.
</div>
#toggle-element {
  background-color: blue;
}

.active {
  background-color: red !important;
}
$("#toggle-button").click(function() {
  if ($("#toggle-element").hasClass("active")) {
    $("#toggle-element").removeClass("active");
  } else {
    $("#toggle-element").addClass("active");
  }
});

Troubleshooting Snippets

These snippets may be used anywhere there is a TODO in the other snippets.

Console Log Snippet & Example

Sometimes it’s helpful to write a message to yourself to check that your JavaScript is working. Use this snippet to write a message to yourself. The message will show up in your browser’s Developer Tools Console tab.

console.log("TODO_MESSAGE");

Replace TODO_MESSAGE with any message you want to write to yourself! This is helpful to see if your code is working or running at all.

You can also log elements by replacing TODO_MESSAGE with an access element snippet. This is helpful to check if your CSS selector is finding/locating the correct elements.

console.log($("TODO_CSS_SELECTOR"));

As an example, let’s say you want to check if your click event is working:

<button id="cookie-accept-button">Accept</button>
$("cookie-accept-button").click(function() {
  console.log("cookie accept button clicked!");
});

If everything is working correctly, you should see the message “cookie accept button clicked!” in the Developer Tools Console when you click the button.

If you don’t see the message when you click the button, that means your code isn’t working correctly. Check that your HTML, CSS, and JavaScript code are correct. The most common mistake is an incorrect CSS selector. (Observe in this example $("cookie-accept-button") should be $("#cookie-accept-button").)