Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Codecademy jQuery section 12/14
$(document).ready(function() {
$('#button').click(function() {
var toAdd = $('input[name=checkListItem]').val();
$(".list").append('<div class="item">' + toAdd + '</div>');
The HTML document has a form element with one text input control, The nameattribute value on the input tag is checkListItem. In addition to the form element, there is an element with id attribute value, button. This is the object that gets a binding to the click event listener.
So we have two listeners in the overall code:
ready() is listening for the DOMContentLoaded event, signalling that the document elements are all in place and ready for script manipulation. The handler that is triggered by this listener is the function it contains, namely, our code.
click() is listening for a mouse click on the Add! button which triggers the handler we have built in.
That function polls the value attribute of the input element and assigns it totoAdd. This is a plain text string. To make it into an HTML string, we add OPENTAG and ENDTAG to the text:
'<div>' + toAdd + '</div>'
and to that we add a class attribute,
htmlString = '<div class="item">' + toAdd + '</div>';
Just to review... This is HTML markup as it would appear in the source document:
<div class="item">plain text</div>
The difference is clear. This one is static, whereas the one above it is dynamically generated. In other words, an HTML string is something that looks like valid HTML, but conforms to the string syntax of JavaScript, namely, quoted, with dynamic content concatenated to opening and closing string expressions..
Lastly, the source document also has an element with class list, to which we intend to add each entered item. That's where the append() method comes in. First we create a jQuery object,
$('.list') // jQuery object of `.list` selector
then call the jQuery method on this object,
We make use of the item class in the next exercise, when we introduce a document on() listener that triggers when an item is clicked. That's to come. Hopefully you have a better feel for what's going on in this program.
It goes without saying that this is only one of many ways. That's where reading and practice come in. Learning those other ways, reasoning their pro's and con's, and testing until the cows come home. Keep the API Documentation close at hand as you learn.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.