Website Development Indonesia

JavaScript Call Random CSS file

Someone talk to stack overflow like this :

I am trying to rotate random CSS sheets via JS - I have the following script but when I am using it - it doesnt seem to work ?

function getRand(){
    return Math.round(Math.random()*(css.length-1));
}
var css = new Array(
'<link rel="stylesheet" type="text/css" href="css/1.css">',
'<link rel="stylesheet" type="text/css" href="css/2.css">',
'<link rel="stylesheet" type="text/css" href="css/3.css">',
'<link rel="stylesheet" type="text/css" href="css/4.css">'
);
rand = getRand();
document.write(css[rand]);

Appreciate any help?


ask and Answer
The best answer is : Try to create the link element programmatically and appending it to the head
function applyRandCSS(){
  var css = ["css/1.css", "css/2.css", "css/3.css", "css/4.css"];
  var randomFile = css[Math.round(Math.random()*(css.length-1))];
  var ss = document.createElement("link");

  ss.type = "text/css";
  ss.rel = "stylesheet";
  ss.href = randomFile;

  document.getElementsByTagName("head")[0].appendChild(ss);
}

Subscribe to receive free email updates:

0 Response to "JavaScript Call Random CSS file"

Post a Comment

Bila Ada posting yang kurang, atau error atau yang lainnya, silahkan tinggalkan komentar agar artikel/post di perbaiki.
Jangan Lupa Cek Box "Notify Me" agar tahu komentar kamu dibalas oleh saya.

If there are any posts that are missing, or error or anything else, please leave a comment for the article / post to be fixed.
Do not Forget Check Box "Notify Me" to know our comments replied by me.

Disqus Comments