0

I have a little problem which is the following:

I have a button which allows to generate html code, example:

               $( "#addBlockArray" ).click(function() {
     
       let idunique =  Math.floor(Math.random() * 100000);
     
           let array = 
           '\
           <divSpecialSelected class="selectedbloccss"  id= ' + idunique + '> edit\
           <table class="table table-hover" contenteditable="true"> \
       <thead>\
         <tr>\
           <th scope="col">#</th>\
           <th scope="col">First</th>\
           <th scope="col">Last</th>\
           <th scope="col">Handle</th>\
         </tr>\
       </thead>\
       <tbody>\
         <tr>\
           <th scope="row">1</th>\
           <td>Mark</td>\
           <td>Otto</td>\
           <td>@mdo</td>\
         </tr>\
         <tr>\
           <th scope="row">2</th>\
           <td>Jacob</td>\
           <td>Thornton</td>\
           <td>@fat</td>\
         </tr>\
         <tr>\
           <th scope="row">3</th>\
           <td colspan="2">Larry the Bird</td>\
           <td>@twitter</td>\
         </tr>\
       </tbody>\
     </table>\
     </divSpecialSelected>\
           '
     
           $( "#blocArray" ).append( array);
     
     
     });

However, when this code is generated, I am unable to use selectors to do actions on it

$("divSpecialSelected").on('click', function () { // that dont work, he dont find this selector
console.log("aaa");
document.getElementById(this.id).addEventListener('mousedown', mouseDown, false);
localStorage.setItem('id', this.id);
window.addEventListener('mouseup', mouseUp, false);

});

I think because it is not in the DOM loaded at the start. But how could I get around this problem?

Heimdall
  • 1
  • 3
  • Wrap in `$(function() { .... })` and delegate - also what is a `divSpecialSelected` ? Why not use proper HTML? – mplungjan Nov 08 '21 at 15:08
  • it's already in a function, I edit the post I wanted to test, because it allowed me to clearly delimit the base divs and my personal divs – Heimdall Nov 08 '21 at 15:16
  • Also do not set an event handler on something else IN a click event handler – mplungjan Nov 08 '21 at 15:25
  • You do not need to set a mousedown listener in a click event. I think you mean to do this: `$(function() { window.addEventListener('mouseup', mouseUp); $('#blocArray').on('click', 'divSpecialSelected', function (e) { mouseDown(e); localStorage.setItem('id', this.id); });});` – mplungjan Nov 08 '21 at 15:28

0 Answers0