Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jquery click event only works once

I am trying to make a button that adds list items to an unordered list.

The button to add a list item works, but it only works once. I would like it to add an empty list item each time the button is clicked. Google referred my to the on() and live() methods, but those didn't seem to work.

So...why does the button only work once?

Here is what I am talking about in codepen http://bit.ly/1sUKOzc

<button id="button">Add List Item</button>

<ul id="list">
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>
var $listItem = $("<li></li>");

$('#button').click(function(){
  console.log('the button has been clicked');
  $('#list').append($listItem);
});

2 Answers

Hello John,

I think you need to move the creation of the list item inside your button callback function, so that a new list item is created with every button click.

Hope this helps.

-Agapito

Great Success Thanks Agapito Cruz !