Toby
Toby

Reputation: 81

Add styling on click with dynamically created DOM elements

I want to create a border around an image that's contained within a div when it's selected and then remove it when it's deselected. How do I get the ID of the div selected?

 function displayLive()
            {
              var previous = null;
              var current = null;
              setInterval(function()
              {
                $.ajax({
                  url: '/showLive',
                  dataType: 'json',
                  contentType: 'application/json',
                  success: function(response) 
                  {
                    current = JSON.stringify(response);
                    if(previous !== current)
                    {
                      var obj = JSON.parse(response);
                      console.log(obj);
                      for(var i = 0; i < obj.active.length; i++)
                      {
                        if($(document.getElementById(obj.active[i].userNameData)).length == 0)
                        {
                          if(obj.active[i].active === true)
                          {
                            $('.left').prepend($('<div/>', {class: 'profTemp', id: obj.active[i].userNameData}).append(
                              $('<img/>', {src: obj.active[i].profiler, width: 40, height: 40}),
                              $('<span/>', {text: " " + obj.active[i].userNameData}))); 
                          }  

                        }
                        else if(obj.active[i].active === false)
                        {
                          $(document.getElementById(obj.active[i].userNameData)).remove();
                          console.log("getting in false");
                        }
                      }
                    }
                  }
                }); 
                previous = current; 
              }, 2000);   
            }

here'a a template

Upvotes: 0

Views: 53

Answers (1)

Michael Coker
Michael Coker

Reputation: 53709

Assign a click handler via $(document).on('click', '.profTemp', function() {}) to trigger the click event on the document so it will work with dynamically added elements, then toggle a class on the div and use that as the state for whether it's clicked or not, and reference the class to draw your border.

$('body').append('<div class="profTemp">  <img class="img" src="https://i.sstatic.net/2C22p.jpg"></div>');

$(document).on('click','.profTemp',function() {
  $(this).toggleClass('selected');
})
.profTemp {
  display: inline-block;
}
.selected img {
  border: 5px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions