Calling all $(".turtle")s!
Goals:
- Use jQuery to access and manipulate collections of HTML elements
- Access additional CSS features embedded in Pencil Code
Coding Snippets:
$
is an alias for thejQuery
function.jQuery
(i.e.,$
) returns all HTML elements meeting a search criterion, such as the<body>
element or all elements with class type'turtle'
.- Use the object returned by
jQuery
to simultaneously manipulate all elements referenced in the collection. - Access individual elements in a jQuery collection using a for x in loop. Make the element behave like a sprite by wrapping it in a new jQuery object.
Math and Computer Concepts:
- In the previous lesson, we used the
jQuery
function with id-selector syntax. The examples above illustrate how to select all elements of a specific type or class, using element-selector syntax and class-selector syntax, respectively. The former states the element type as a string (e.g.,$("body")
) and the latter is a string containing the class name prepended by a period (e.g.,$(".turtle")
)
- jQuery returns HTML elements in a jQuery wrapper object, which you can subsequently control using familiar Pencil Code functions. When
jQuery
returns a collection of HTML elements, that object behaves much like a collective sprite. But when accessing individual elements in a jQuery collection, that element must be wrapped in its own jQuery object before it can be manipulated as a sprite!
Activities:
Save each of the following in a folder called Selectors.
- NoMoreDot2000: Use jQuery CSS element selector syntax to gain access to the HTML
<body>
element. Then use thecss
method to set thebackgroundColor
property. SetTheScene: Instead of setting a color, decorate your background using an image. Set the
<body>
element'sbackground-image
property to a string that identfies the image's URL, e.g.,"url('https://www.pngall.com/wp-content/uploads/2016/07/Space-PNG-HD.png')"
- TeamTurtlesTwo: Create a new version of TeamTurtles with 50 sprites that you control with a single
jQuery
reference. - AlphabetSoup: Write a script that positions letters in a message randomly about the screen. Rather than create an
id
property for each label, use$
to access all thelabel
elements. Iterate through this collection to unscramble the message, one letter at a time.