Search code examples
javascriptjqueryuserscripts

Setting click to not created elements


this is my first question here and I hope I'm asking it correct. I'm making an userscript. The website has a chat and when a user for example clicks a message it should copy it. The website has removed right click and selecting. I know how to copy the message, but I don't know how to add the click feature part.

This is the code I have so far:

$(document).ready(function(){
      $('.msg').click(function(){
      $('#someinput').val($(this).text())
      .select();
      document.execCommand('copy');    
      });
});

This gives me the error Cannot read property 'click' of null, and I guess that is because the chat message isn't created yet. How do I fix this?


Solution

  • You must use jQuery event delegation: http://learn.jquery.com/events/event-delegation

    If your .msg elements are inside a container you can write

    $(document).ready(function() {
        $('#container').on('click', '.msg', function() {
            // your click function
        });
    });