Event handler


#1

Can someone explain better than Codeacademy the reason why the separate 'on' event handler is necessary to remove the html objects in question?

On 5.14, codeacademy says, re: removing html elements under the 'ready' code:

"The problem is that it won't work—jQuery looks for all the .items when the DOM is loaded, so by the time your document is ready, it's already decided there are no .items to .remove(), and your code won't work."

This makes no sense to me, as earlier in this same chapter (5.5), we removed html elements that were only added using jquery. Therefore they didn't exist when the page was loaded, yet we still were able to remove them.

I'd like to have a handle on the theory behind the 'on' event handler, so if someone could explain to me just what is going on, I'd really appreciate it.

THanks!


#2

Hey Paul,

This is a great question, and it's easy to get confused with this type of stuff :)

In 5/5, we add the element, then remove it. By the time the computer gets to the code that removes it, <p> has been added to the page, so the selector finds it without a problem.
In this exercise though, the computer runs through the code, and since we haven't added any .items to the list by the time we get to the $('.item').click(...); section, the $('.item') returns null, since there are no .items. Using $(document).on('click', '.item', function() {...}); works differently though. It listens for clicks anywhere on the page, then checks if they're on an element with the item class, and if so, it runs the code.

Does that help you understand it?


#3

Thanks Zystvan! I get it now!


#4

This topic is solved.