H
H
hadaev_ivan2014-05-18 11:35:37
JavaScript
hadaev_ivan, 2014-05-18 11:35:37

Google Chrome Extension: addEventListener for created button

'sidebar' is a div that is created by the content_script of my extension, it has a 'button' button in it, why doesn't the below code work?

var sidebar = document.getElementById('sidebar');
    if (sidebar && sidebar.addEventListener) {
      sidebar.addEventListener('click',
          function (element) {
            switch (element.id) {
              case 'button':
                alert('button');
                break;
            }
          }, false);
    }

Thanks for the help)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hadaev_ivan, 2014-05-18
@hadaev_ivan

I'm sorry) I didn't understand)
the code problem was that the "element" variable stored the "MouseEvent" object, and not the html element object. To access it, you had to use "element.srcElement"
Actually replaced "element.id" with "element.srcElement.id" - everything became as it should)
Working code:

var sidebar = document.getElementById('sidebar');
    if (sidebar && sidebar.addEventListener) {
      sidebar.addEventListener('click',
          function (element) {
            switch (element.srcElement.id) {
              case 'button':
                alert('button');
                break;
            }
          }, false);
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question