Search code examples
javascriptcssstylesheet

How to make a onclick function random?


Could you guys look at my edited code based on the replies please.

I have this code right now in my javascript:

 function test(sheet)
 {
     document.getElementById('pagestyle').setAttribute('href', sheet);
 }

And I want to use this function to change my stylesheet

onclick="test('CSS/katy.css')"

My question is, how do I make the "katy.css" a random css file from my folder.

I was thinking about an array but I don't know how to apply this.

var cssName=new Array(3)

cssName[0]="<link rel='stylesheet' type='text/css' href='CSS/katy.css'>";
cssName[1]="<link rel='stylesheet' type='text/css' href='CSS/daftpunk.css'>";
cssName[2]="<link rel='stylesheet' type='text/css' href='CSS/wiliam.css'>"; 

edited button:

onclick="test('CSS/' + cssName1[rndIndex])" 

Edited test function:

 function test(sheet)
 {
    var cssName1=new Array(3)

    cssName1[0]="<link rel='stylesheet' type='text/css' href='CSS/katy.css'>";
    cssName1[1]="<link rel='stylesheet' type='text/css' href='CSS/daftpunk.css'>";
    cssName1[2]="<link rel='stylesheet' type='text/css' href='CSS/wiliam.css'>";  
    var rndIndex= Math.floor(Math.random()*3);

     document.getElementById('pagestyle').setAttribute('href', sheet);
 }

Solution

  • You could generate a random int number in [1,3], with the following way:

    var rndIndex = Math.floor(Math.random()*3);
    

    Then you can use the generated index to get the css you want:

    onclick="test(cssName[rndIndex])";
    

    Note In the cssName table it would be better you place only the corresponding href's. I am saying this, because as I noticed in the declaration of your function you set the value for the href attribute.

    Update I would suggest, as you will see in the fiddle here to declare a parameterless function for your purpose. I have declared the setCss function and then there select the pagestyele element and set it's attribute called 'href' to one of your css randomnly.