Overview
This brief article presents a solution to having multiple Buttons associated with multiple Web server functions and processing them with a single Javascript handler. For this solution, we make use of the dataset property of an HTMLElement. This property is coded in HTML as data-<attribute> and is retrieved in the common Javascript Button handler using the dataset property of the target element (Button) (see Javascript Listing 2).
HTML
Each button has a common class (e.g., button-action), and this class is used to select and add a common Javascript handler for each click. In this example, the data-action attribute defines the function that will be called on the Web server (e.g., via a GET method).
<button class="button-action" data-action="func1">Function 1</button> <button class="button-action" data-action="func2">Function 2</button> <button class="button-action" data-action="func3">Function 3</button>
Javascript
Note that we use our own internal Javascript library referenced to the '$$' symbol. For example:
function $$(selector, el) { if (!el) { el = document; } return el.querySelectorAll(selector); }
The Javascript code below creates a click handler for each Button using a common handler. The common handler specifies the desired URL using the function passed in the dataset property (e.g., /funcs/func1).
$$('.button-action').forEach(function(val, idx, obj) { val.addEventListener('click', function(e) { e.preventDefault(); var tgt = e.target; $.get('/funcs/' + tgt.dataset.action, function(resp) { // process reponse }); }); });
Django / Python
For those using the Django Web Framework on the server, here's what our url pattern looks like:
url(r'^funcs/(?P<action>[a-z\_]*)', funcs, {}),
Our view function would be called as shown:
def funcs(request, action):