click handler not working in content script

I have the following code being run via chrome extension content script. I can't get the click handler to work though. Via the run_at flag in manifest.json the script is being run at document_end. Any ideas?

$(document).ready(function () {
  var enabled = true;

  $('body').append("<button id='#alarmButton'>Disable Alarm</button>");

  $('#alarmButton').on('click', function () {
    console.log('clicked');
    if (enabled == true) {
      enabled = false;
      $('#alarmButton').text('Enable Alarm');
    } else {
      enabled = true;
      $('#alarmButton').text('Disable Alarm');
    }
  });
});

Answers


You don't need to add # in your id attribute.

Change

$('body').append("<button id='#alarmButton'>Disable Alarm</button>");

to

$('body').append("<button id='alarmButton'>Disable Alarm</button>");

and for click event use:

$('body').on('click', '#alarmButton', function () {})

Jsfiddle


You can bind the click event to the button, on create time, before appending to the document. This should work:

$(document).ready(function() {
  var enabled = true;    
  $("<button id='#alarmButton'>Disable Alarm</button>")
    .appendTo('body')
    .click(function() {
      console.log('clicked');
      if (enabled == true) {
        enabled = false;
        $('#alarmButton').text('Enable Alarm');
      } else {
        enabled = true;
        $('#alarmButton').text('Disable Alarm');
      }
    });
});

Need Your Help

string offset as an array

php drupal multidimensional-array fatal-error

I am working in drupal 6, but I think this is more of a php related question than a drupal question.

Get the values from console(FIREBUG) using jquery

jquery console firebug

Is it possible to read the output of console.log with jQuery? I mean if I am getting some value in console(FIREBUG) using console.log, is there a way to get it in a jquery function using some means?