0

I've implemented the Google FastButton script into a web page. Following:

Trying to implement Google's Fast Button

The code works great. My question is how do I implement this for multiple buttons. I have several buttons that are dynamically created. I don't want to define each button with its own function. Can I use this script with another function that passes some variable.

For example, <button id="quick" onclick="someFunction(24);">button</button>

Current implementation

new FastButton(document.getElementById('quick'), function() {
       alert("hello");
    });
<button onclick="onLayerClick(8)">8</button>
Community
  • 1
  • 1
scriptdiddy
  • 1,207
  • 3
  • 17
  • 31

1 Answers1

1

Here's one way to do it: According to the link you pasted, the FastButton prototype accepts a function as its second argument (this.FastButton = function(element, handler)) and passes the click event to that function. So if you do something like this:

HTML:

<button id="quick">24</button>

JS:

var myHandler = function(event) {
    var el = event.target;
    console.log(el.innerHTML);
}

new FastButton(document.getElementById('quick'), myHandler);

Then the myHandler() function will have access to the DOM element where the click event originated (event.target), which will be whatever button was clicked. So you'll have access to that button's innerHTML, or you could put a data-mynumber="24" attribute on the button and use el.getAttribute("data-mynumber") instead of el.innerHTML... However you want to identify the button is up to you.

glomad
  • 5,539
  • 2
  • 24
  • 38
  • Your logic seems to work for the first element. But then every element after that with the id "quick" doesn't work. How can I apply this to every id or class with "quick" – scriptdiddy Feb 07 '13 at 05:41
  • You can't have more than one DOM element with the same id. If you instead use a class, you can do something like this (assuming jQuery): `$(".quick").each(function() { new FastButton(this, myHandler); });` – glomad Feb 07 '13 at 05:45
  • I'm using javascript. How would I do it with standard js – scriptdiddy Feb 07 '13 at 05:50
  • `var buttons = document.getElementsByClassName("quick"); for(var i = 0; i < buttons.length; i++) { new FastButton(buttons[i], myHandler); }` is one way – glomad Feb 07 '13 at 15:31