Chapter 3: DOM Manipulation and Event Handling
Activity 3 – Implementing jQuery
You want to make a web app that controls your home's smart LED light system. You have three LEDs that can be individually turned on or off, or all toggled together. You must build a simple HTML and jQuery interface that shows the on state of the lights. It must also have buttons to control the lights.
To utilize jQuery to build a functioning application, follow these steps:
Create a directory for the activity and in that directory, in the command prompt, run
npm run init
to set uppackage.json
.Run
npm install jquery -s
to install jQuery.Create an HTML file for the activity and give the HTML block a body.
Add a style block.
Add a div to hold all of the buttons and lights.
Add a
script
tag with the source to thejQuery
file.<script src="./node_modules/jquery/dist/jquery.js"></script>
Add a
script
tag to hold the main JavaScript code.Add a
light
class to the CSS style sheet with the following settings:Width and height:
100px
Background-color:
white
Add a toggle button to the div by using the
id=toggle.
Add a div to hold the lights with the id
lights
.Add three divs inside this div.
Note
Each div should have a div with the
light
class and a button with thelightButton
class.
In the code script, set up a function to run when the DOM loads:
$( () => { ... } )
Select all the
lightButton
class buttons and add on-click handler that does the following:Stops the event propagation and selects the element target and get the
light
div by traversing DOM.Check the
lit
attribute. If lit, unset thelit
attribute. Otherwise, set it withjQuery.attr()
Change the
background-color css
style to reflect thelit
attribute withjQuery.css().
Select the
toggle
button by ID and add an on click handler that does the following:Stops the event propagation and selects all the light buttons by CSS class and trigger a click event on them:

Code:
activity.html
The following is the condensed code. The full solution can be found at activities/activity3/index.html
.
$( '.lightButton' ).on( 'click', e => { e.stopPropagation(); const element = $( e.target ).prev(); if ( element.attr( 'lit' ) !== 'true' ) { element.attr( 'lit', 'true' ); element.css( 'background-color', 'black' ); } else { element.attr( 'lit', 'false' ); element.css( 'background-color', 'white' ); } } ); $( '#toggle' ).on( 'click', e => { e.stopPropagation(); $( '.lightButton' ).trigger( 'click' ); } );
Snippet 3.32: jQuery function application
Outcome:
You have successfully utilized jQuery to build a functioning application.