Back to Posts

quick and lazy random titles šŸ’»

redesigned

Just to add some context to this: I refreshed the blog design again, and in part with stealing every idea I come across Iā€™ve made a really quick and dirty random tagline picker thing. For a demo, refresh this page a few times.

step one: create an array

Something as quick and dirty as Iā€™m making here needs a dirty and quick array:

var tags = [
  'Registered CSS offender.',
  'Mum, I\'m on the Internet!',
  '#implications',
  'Powered by magic beans',
  'Brought to you by Caprisuns',
  'A new design every week or your money back',
  'Come on, grab your friends!',
  'Follow me on Twitter!',
  'Steamed hams',
  'My other blog gets updates',
  '<i>"lol"</i> - you'
];

step two: pseudorandom number generator

Anyone whoā€™s ever done ā€œrandomnessā€ in computer programming before knows the general formula random() * (max - min + 1)) + min (where random() generally gives a number between 0 and 1). I wonā€™t pretend to understand or remember how this works, however if youā€™re interested in the how check this excellent explanation on StackOverflow out.

Now since our array starts at 0 (so we have no min), our nextā€“and only otherā€“line can just be:

var random_tag = tags[Math.round(Math.random()*(tags.length-1))];

step three: itā€™s lit

Throw in a cheeky tag into where you want your random tag:

<span id=random-tag></span>

then add a not so cheeky document.addEventListener to insert random_tag into your page:

document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById("random-tag").innerHTML = " " + random_tag
})

thereā€™s probably a better way to do this

Full disclosure: I generally have no idea what Iā€™m doing, so if you know of or find a better way of performing this fairly simple task: go ahead and use it.