Joel Lark
Joel Lark

Reputation: 29

Using click events on dynamically added DOM elements

Question: Why does it work when element is hard-coded into HTML but does not work when added dynamically via Jquery?

I am teaching my self Jquery within my self learning of javascript, and I am just creating a simple troubleshooting assistant app for the sake of learning. I actually have my code posted here: https://repl.it/@jllrk1/OrganicBothRay.

The way I have it set up so far is the user clicks on the header block to begin, which is set up with a onetime click function to create a UL for some products at my job in which we provide IT Service.

I then am trying to be able to click each product in that list to pull troubleshooting walkthroughs for that specific product (it will guide the user based on what they click or enter).

For testing purposes I just tried having the background of the list item in which is clicked to change to red.

I cannot get this to work, or my console.log to fire telling me that the function is not getting called.

however, if I hard code in the ul into the html, using the same code for the click events, it works just fine.

Am I doing something wrong?

Just looking to gain a better understanding!

$(function () {
//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_
//set up variables
//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_
//var $liItems = $('.product li');
var $chief = $(".chiefblock");
var $container = $("#container");
var $this = $(this);
var $error = '';



var initList = function () {
  console.log("initList initiated");

        $container.append('<div class="product"><ul><li>TASC</li><li>TABE</li><li>Las Links</li><li>TerraNova</li><li>E-Direct</li></ul></div>'); 
    $("p").text("Start by selecting a product");

}


var navItems = function (event){
      console.log("navItems initiated");
      var target = $(event.target);
          if (target.is("li") ) {
            target.css("background-color", "red" );
          }



}       
var nObject = function () {
        $container.append('<div id = "tasc"><h2>Tasc</h2><p></p></div></div>');
    $('#newItem').prepend('<h2>Item</h2>');




}


$('.chiefblock').one('click', initList)
    //$('li').on('click', navItems) this i tried and does not work
$('#newObject').on('click', nObject)
$('ul').on('click', navItems)
//$liItems.on('click', navItems)this i tried and does not work


});

Upvotes: 1

Views: 335

Answers (1)

cb64
cb64

Reputation: 855

for dynamically added DOM elements use

$(document).on('click', '#element', function() {
    console.log($(this))
})

Upvotes: 1

Related Questions