0

I've searched quite a bit, and none of the answers I've found have worked 100%.

Basically, I want the popup to show a handful of buttons, then call the same function with different parameters. Concept:

<button onclick="foo(1,2);">Button 1</button>
<button onclick="foo(2,3);">Button 2</button>

I've tried a few simple and direct methods, none of which work. If I take the code out of the function, and have popup.js contain the code, it works (my function is fine).

I've tried:

$('#btn1').click(function(e) {
    alert('btn1');
});

as well as

document.getElementById('btn1').addEventListener('click',doSomething(1,2));

Also, i've tried adding the button addEventListener inside of a document.addEventListener('DOMContentLoaded', function() {....});

The curious part is that if my popup.js contains button.addEventListener, the first one is fired upon clicking the browser action, and then nothing works. This happens regardless of whether the click event listner is inside of a DOMContentLoaded listener or not.

I have a feeling this is a CSP issue, but I can't seem to get it to work.

For those scanning for a question mark: From within a popup.html/popup.js, how can I call a single function with different parameters based on an onclick event?

Thom Seddon
  • 1,485
  • 2
  • 15
  • 25
Curtis Mattoon
  • 4,642
  • 2
  • 27
  • 34

1 Answers1

2

Issues

I'm not sure if it was just through your abbreviation when copying to SO but none of the code you have given would work "as pasted":

  • You have no id's on the buttons so binding to the id (I assume this is just because they weren't relevant in the first paste!)
  • The second paste uses the jQuery library and so you would need to make sure jQuery is included and allowed: https://stackoverflow.com/a/10928761/969807
  • In the third paste, the second parameter of addEventListener should be a function accepting the event as the first and only parameter (if wanted). (Read On)

Solution

The most common way to bind an event in the scenario you describe would be like so:

document.getElementById('btn1').addEventListener('click', function (){
    foo(1, 2);
}, false);

 

However if there were a lot (or a variable amount) of buttons, I would probably do it like so:

popup.html:

<div id="buttons">
  <button data-param1="1" data-param2="2">Button 1</button>
  <button data-param1="2" data-param2="3">Button 2</button>
</div>

popup.js:

var els = document.querySelectorAll('#buttons button'),
    i, total, param1, param2;

for (i = 0, total = els.length; i < total; i++) {
  el = els[i];

  param1 = parseInt(el.getAttribute('data-param1'));
  param2 = parseInt(el.getAttribute('data-param2'));

  el.addEventListener('click', function (){ foo(param1, param2) }, false);
}
Community
  • 1
  • 1
Thom Seddon
  • 1,485
  • 2
  • 15
  • 25