29.07.2016 Views

front-end-developer_1_

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Front-End-Developer - Level 1<br />

Now, if we click Say "hello" and then the message, we get our alert! But there's a problem: if<br />

we click the button twice, clicking the last message will open the alert twice. And if we click<br />

the button again, the last message will open the alert three times, and the middle message<br />

will open it twice. What's happening is that the first time we click the button, $('.delete')<br />

only finds a single message in each list, and attaches an event handler. But the next time we<br />

click the button, that first message is already on the page, and a second event handler is<br />

attached to it. And each time we click the button again, another event handler is attached to<br />

every message on the page.<br />

What we want is to only attach handlers to the message we most recently inserted. Since<br />

we're inserting them at the top of each list, we can select one of the s, look through its<br />

child elements (the s), and select the first one of them:<br />

$("ul#user").children("li").first().click(function() {<br />

alert('hi');<br />

});<br />

$("ul#webpage").children("li").first().click(function() {<br />

alert('hi');<br />

});<br />

Now, each of the messages only opens a single dialog box when clicked.<br />

Finally, we should replace our callback with the actual code to delete the message:<br />

$("ul#user").children("li").first().click(function() {<br />

$(this).remove();<br />

});<br />

$("ul#webpage").children("li").first().click(function() {<br />

$(this).remove();<br />

});<br />

remove() is pretty straightforward, but what is this ? this is a bit of a tricky concept in<br />

JavaScript, and I'm not going to give it a full explanation here. For now, you can think of it as<br />

referring to whatever was clicked on.<br />

We're done with this rather long lesson. Congrats on making it through!<br />

Summary<br />

Insert within a DOM element at the beginning or <strong>end</strong>:<br />

$('ul').prep<strong>end</strong>('First list item');<br />

$('p').app<strong>end</strong>('New last sentence of the paragraph.');<br />

DOM Manipulation and Traversal<br />

174

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!