Search code examples
jqueryiphoneweb-applicationsmeta

Randomize url in meta tag with jQuery?


I'm using the following meta tag to load a startup image for an iPhone web app:

<link href="apple-touch-startup-image-640x920.png" rel="apple-touch-startup-image">

What I want to do is randomize the image path (01.png, 02.png, 03.png, etc.) when the page loads, e.g.:

<link href="random image path here" rel="apple-touch-startup-image">

Anybody know how to do this with jQuery?


Solution

  • To grab a random object from an array in javascript you can use:

    var randomItem = arr[Math.floor(Math.random()*arr.length)]
    

    Combining this with your request you can do:

    ;(function($, window, document, undefined){
            $(function(){
                var images = ['01.png', '02.png', '03.png'];
                $("[rel='apple-touch-startup-image']").attr("href", images[Math.floor(Math.random()*images.length)]);
            });
    })(jQuery, this, document);