-2

I'm trying to create a chrome extension. I had a problem with the affectation of event for the new element that i append to the dom of site with content. Js

If I add an event to an element' 'for example class' exist already in the page, it works correctly. Just for my new appended element((in the code iadded a button ,the event is just an alert to test))

function tst() {
  myclass = $("._3hg-._42ft");
  myclass = myclass.not(".supp");
  myclass.addClass("supp");
  var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
  for (i = 0; i < myclass.length; i++) {
    result = patt.exec(myclass[i]);
    myclass.append('<button class="fact" id=' + result[0] + ' style="position: absolute;">fact</button>');
  };

  /* this is a simple event*/
  /***********************/
  $(".fact").on('click', function() {
    alert("no event work ");
  });
j08691
  • 204,283
  • 31
  • 260
  • 272

1 Answers1

0

Making somewhat broad assumption here in my answer that it is JavaScript/jQuery related and is NOT an extension...or is so still in that context. You need to attach the event to the container here perhaps for the dynamically created elements. Lots of global stuff, suggested to not do that, updated there.

Appends a lot of buttons perhaps? might need to only hit DOM once but left as-is in this isolated function.

function tst() {
  let myclass = $("._3hg-._42ft")
    .not(".supp");
  myclass.addClass("supp");
  //let result = {};
  var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
  var i = 0; //avoid global
  for (i; i < myclass.length; i++) {
    // broad assumption of the returned value from patt.exec() here
    // not even sure why it needs an id, have a class, use for css
    let result = patt.exec(myclass[i]);
    myclass.append('<button class="fact" id="' + result[0] + '">fact</button>');
  }

  /* attache event to pre-existing element */
  /***********************/
  myclass.on('click', ".fact", function() {
    alert("event works");
  });
}
button.fact {
  position: absolute;
}
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100