Tag Archives: javascript

JavaScript: How To Trigger at a Specific Time CodeUnit 23 JAN 2013

Sometimes you want your web page to do something at a specific time. For example, perhaps you want your page to force a reload at midnight, say if it is being used as a monitor screen and you want to reload it in order to reset browser memory usage.

Anyway, triggering at a specific time using JavaScript turns out to be a fairly simple task, thanks to the useful timing function, setTimeout.

The trick is simple enough. On page load, grab the current timestamp using the Date() object. Then create a new Date() object and manually set its hour and minutes to match the time you want your event to trigger. The difference between the two objects’ times expressed in milliseconds is then used to create a setTimeout event, which naturally will trigger when those milliseconds are up.

Clever.

The following example forces a page reload just before midnight:

//the window reload function. you could of course do anything here
function forceMidnightPageReload() {
        window.location.reload(true);
}

//helper function to build up the desire time trigger
function forceMidnightPageReloadGetTargetTime(hour,minute) {
  var t = new Date();
  t.setHours(hour);
  t.setMinutes(minute);
  t.setSeconds(0);
  t.setMilliseconds(0);
  return t;
}

//get your offset to wait value
var timetarget = forceMidnightPageReloadGetTargetTime(23,59).getTime();
var timenow =  new Date().getTime();
var offsetmilliseconds = timetarget - timenow;

//if it isn't midnight yet, set a timeout.
if (offsetmilliseconds >= 0){
setTimeout(function(){forceMidnightPageReload();}, offsetmilliseconds);
}

Useful.

JavaScript: A Simple Function to Return a Sorted and Unique Array CodeUnit 28 OCT 2012

I came across this useful little JavaScript code snippet which given a simple input array, will both sort it and ensure that it contains unique values.

If you take a look at the code, you’ll notice that the trick is to first sort the array, and once that has been taken care of by JavaScript’s native sort function, we then loop through the array checking that the previous element doesn’t match the element we’re trying to add.

Simple, but works well for very simply arrays which need to be unique in nature (e.g. phone numbers before a batch SMS operation.)

function sort_unique(arr) {
    arr = arr.sort(function (a, b) { return a*1 - b*1; });
    var ret = [arr[0]];
    for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
        if (arr[i-1] !== arr[i]) {
            ret.push(arr[i]);
        }
    }
    return ret;
}
console.log(sort_unique(['237','124','255','124','366','255']));
//["124", "237", "255", "366"]

Nifty.

How to Use Percentage Sizes for Your FancyBox CodeUnit 13 OCT 2012

I’m a huge fan of the jQuery-driven FancyBox and make use of it in just about all of my web development work.

This is a handy little trick to use percentage (%) values for a fancybox implementation’s width and height, thereby making it easier to specify a fancybox that will work regardless of screen size.

(If you are familiar with fancybox then you are aware that it requires height and width values to be passed to it as pixel values.)

Note that I’m assuming that you are making use of the wonderful jQuery JavaScript library here.

//setting a width of 90% and a height of 75%
var fbwidth = Math.ceil(($(document).width()*90)/100);
var fbheight = Math.ceil(($(document).height()*75)/100);

$('#versioninghistory').fancybox({'type':'iframe','autoScale':true, 'width': fbwidth, 'height':fbheight, 'centerOnScroll':true});

Looking at the snippet above, you’ll see that we are first calculating the pixel value of the desired percentage value based on either the screen width or height (using jQuery’s document related functions), and then passing it through to the fancybox declaration.

Nifty.

How to Refresh a DataTable without Losing Your Current Page or Ordering CodeUnit 28 MAY 2012

DataTables is a fantastic plug-in for the jQuery Javascript library that I use for pretty much all my web development projects. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table – in other words, it creates useful dynamic, with oodles of extra functionality, tables out of plain old vanilla HTML tables.

Anyway, there is often a need to be able to refresh your datatable after applying some action to the source data, and the usual method of forcing a refresh is by calling the standard fnDraw() function on the table object. However, whilst this will redraw the table, it will basically reset you completely, removing any filtering and jumping back to page 1 if you have a table with pagination.

So not ideal.

Thankfully one of the DataTables forum guys came up with a handy bit of extension code which introduces a new function called fnStandingRedraw() which extends the datatables API and allows you to fresh the datatable without losing your current view.

To implement, simply put the following code into a .js file and load it after you load the standard datatables.js library:

$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
    //redraw to account for filtering and sorting
    // concept here is that (for client side) there is a row got inserted at the end (for an add)
    // or when a record was modified it could be in the middle of the table
    // that is probably not supposed to be there - due to filtering / sorting
    // so we need to re process filtering and sorting
    // BUT - if it is server side - then this should be handled by the server - so skip this step
    if(oSettings.oFeatures.bServerSide === false){
        var before = oSettings._iDisplayStart;
        oSettings.oApi._fnReDraw(oSettings);
        //iDisplayStart has been reset to zero - so lets change it back
        oSettings._iDisplayStart = before;
        oSettings.oApi._fnCalculateEnd(oSettings);
    }
     
    //draw the 'current' page
    oSettings.oApi._fnDraw(oSettings);
};

Now on your page code, you can simply ask for a refresh by doing this:

//var oTable1 = $('#mytable').dataTable();
oTable1.fnStandingRedraw();

Nifty.

Related Link: http://datatables.net/

How to create a Variable Length String of Random Characters using JavaScript Programming 04 MAY 2012

Generating random strings is always necessary when working with things like voucher or password generation, and so today’s quick JavaScript function looks at returning a specified length of string containing a a selection of randomly selected characters and numbers.

The function works by specifying a string containing all the characters you wish to be used in your randomly generated string. Using the random() function and mixing it up a little to generate essentially a character position, we can grab a character off the previously mentioned character string. Rinse and repeat for the desired length of string, adding everything together to at last come up with your string of random characters.

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

Nice and random, just like this image.

Nifty.

Using a jQuery selector on an ID containing a Pipe (|) Character Programming 24 FEB 2012

I’m quite fond of using the pipe (|) character in tag, id and name properties because it just seems visually such a great delimiter to use when stuffing a string full of useful information to be extracted via splitting or exploding at a later stage.

However, here’s a nasty one which you might not be aware of – jQuery selectors do in fact no enjoy special characters like the pipe ‘|’ – for the very reason that it’s a special character!

So running a selector on an ID which contains a | in the normal fashion will fail (i.e. not find anything):

$('#id|123')

To get around identifiers that use special characters like our friend the |, you need to delimit it so:

$('#id\|123')

And now you know! :)

JavaScript: How to Implode (Flatten) an Array into a String Programming 17 FEB 2012

Coming from PHP, I’m well versed in using the handy implode function to flatten an array into a string, specifying the delimiter character to be used to indicate the border between the flattened array elements.

Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “join”.

From the official definition: The join() method joins all elements of an array into a string, and returns the string.

The elements will be separated by a specified separator. If this is ommitted, then the default separator of a comma (,) will be used.

A few examples on using join:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

//a few example usages
document.write(fruits.join() + "<br />");
document.write(fruits.join("+") + "<br />");
document.write(fruits.join(" and "));

//the output:
//Banana,Orange,Apple,Mango
//Banana+Orange+Apple+Mango
//Banana and Orange and Apple and Mango

Useful.

JavaScript: How to Explode a String into an Array Programming 13 FEB 2012

Coming from PHP, I’m well versed in using the handy explode function to force a string into an array, using a specified delimiter character to chop up the string into the little bits that are to be stored in the array.

Happily for me, plain old vanilla JavaScript also has this ability built into the language, choosing to call its version of this functionality “split”.

From the official definition: The split() method is used to split a string into an array of substrings, returning the new array containing the substrings.

It accepts two parameters, namely the separator and the limit, both of which are actually optional by the way. The separator parameter is where you specify the delimiter character (if you omit this, the entire string will be stuffed into a single element array ). The optional limit parameter if set will control the number of splits.

A few examples on using split:

var str="How are you doing today?";

//some split usage examples
document.write(str.split() + "<br />");
document.write(str.split(" ") + "<br />");
document.write(str.split("") + "<br />");
document.write(str.split(" ",3));

//the output (',' indicates array boundary)
//How are you doing today?
//How,are,you,doing,today?
//H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
//How,are,you 

Useful.

Jquery: How to Set the Selected Radio Button via a Script Programming 10 FEB 2012

If you develop websites and work with JavaScript, but have never heard of jQuery before, then it is probably best that you start reading up on it right now. After all, as they like to put it themselves, jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript!

Now we’ve seen that to retrieve the value of the checked radio button from a group of radio buttons using jQuery, we need to use the input[]:checked selector and then grab the val string as you would normally do.

In practice, this process would look like this:

alert($('input[name=myradiobuttons]:checked').val());

Now sometimes you need to programmatically set the selected radio button in your JavaScript script, and thankfully jQuery once again comes to our rescue with its handy selectors.

If we know the value of the radio button to be selected, we can use the same trick as the above sans the :checked segment, and then filter those results with our known value, before finally ending off the selector with the act of setting the checked property.

In practice this would be set out like so:

$('input[name=myradiobuttons]').filter('[value=selectedvalue]').prop('checked',true);

Clever.