Useful Snippets #1

Here are a couple of Javascript snippets that I've found useful in the past weeks:

JS: getElementById Shortcut

Depending on if you use jQuery (or similar libraries), your $ variable may be assigned to that. This example shows how you can utilize the $ variable for a shortcut to getElementById

// Code Snippet from
var $ = function(el){ return document.getElementById(el.replace(/^#/,'')); }
$("header").innerHTML = "Testing $ shortcut!"; //Simple use case
$("#header").innerHTML = "Testing $ shortcut!"; //jQuery-like request

JS: unix timestamp for Javascript

Working between PHP and Javascript, I become really reliant on the time() PHP function for cache busting/request verification. Using Math.round(new Date().getTime()/1000) every time is a pain and takes up valuable bytes in your code. So, I created a function instead:

// Code Snippet from
var time = function(){return Math.round(new Date().getTime()*0.001);}
alert("The current unix timestamp is "+time()); //Prompt the timestamp
$.get("cached.file?"+time(),function(){ ... }); //Cache buster
$.get("ajax.php?timestamp="+time(),function(){ ... }); //Timestamped request

comments powered by Disqus

Old Comments

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +

Add a New Comment

Unless otherwise stated, all of the site's contents (including articles, blog post and code snippets) is:
Copyright © Kenneth Tsang 2014