0

When i add an <li> with the css below i can select the item but if i add it using .append i cannot what am i doing wrong?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<ul id="events" class="select" name="events">
<li>Opt 1</li>
</ul>

.

$('ul.select li').click(function(e){
  var item = $(e.target);
  item.addClass('selected');
  item.siblings().removeClass('selected');
  $('#events').val(item.text());
});

$('#events').append('<li>Opt 2</li>');

.

ul.select {
   list-style: none;
   margin:  0;
   padding: 2px;
   height:50vh;
   overflow-x: hidden;
   border: 1px solid grey;
   width: 50vw;
   background-color: black;
   color: white
}

ul.select li {
   padding: 2px 6px;
}
ul.select li:hover {
   cursor: pointer;
}
ul.select li.selected {
   background-color: lightgrey;
   color: black;
}

See Fiddle for example of issue.

OSKM
  • 728
  • 14
  • 25
  • Your link is broken – Lixus Jun 12 '17 at 18:45
  • 1
    The event handler you set up doesn't extend into the future, it is only applied to elements that already exist. If you add new `
  • `s you have to set it up again. Just wrap it in a function and call that after appending.
  • –  Jun 12 '17 at 18:46
  • @Lixus link now sorted - thanks for flagging – OSKM Jun 12 '17 at 18:47
  • CSS Loads in when the page does, if you add elements dynamically, the CSS wont affect it – AzizurRahamanCA Jun 12 '17 at 18:48
  • @RandomDeveloper 100% incorrect – j08691 Jun 12 '17 at 18:48
  • @ChrisG Thanks - that is the issue, sorry for a simple question, very new to html and JS. – OSKM Jun 12 '17 at 18:52