Posts

Showing posts with the label example

Implementing a raffle in JavaScript

At two recent occasions, there were copies of “Speaking JavaScript” to be raffled off. This blog post describes two ways of drawing winners via JavaScript. There is a list of the attendees’ names If there is a list of the attendees’ names, drawing a winner is relatively easy. In my case, it was a MunichJS meetup and a list of names was online, as a web page . In a browser console, I accessed the DOM to make a random pick: // Once: var nameElements = document.querySelectorAll('span.D_name'); var names = [].map.call(nameElements, function (elem) { // (1) return elem.textContent.trim(); }); // Repeatedly: names[Math.floor(Math.random() * names.length)] // (2) At (1) I invoke map() generically , because the result of querySelectorAll() is not an array and does not have that method. At (2), I use Math.random() and Math.floor() to compute an integer in the range [0, names.length ). You don’t know the attendees’ names If you don’t have a list o...