Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Javascript function

    Hi,
    I am newbie into javascript and i need one function. For example i have 4 divs (div1, div2, div3, div4) and i want to give one specific css class (css1) randomly in only two divs when fired pageload event.
    Thnx in advance.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,011
    Thanks
    203
    Thanked 2,538 Times in 2,516 Posts
    This assigns the classname css1 to two divs randomly on page load.

    Code:
    <html>
    <head>
    </head>
    
    <body onload = "assignClass()">
    
    <div id = "div1">Content of Div1</div>
    <div id = "div2">Content of Div2</div>
    <div id = "div3">Content of Div3</div>
    <div id = "div4">Content of Div4</div>
    
    <script type = "text/javascript">
    function assignClass() {
    var thedivs = ["div1", "div2", "div3", "div4"];
    var shuffled = shuffle(thedivs);
    document.getElementById(shuffled[0]).className ="css1";
    document.getElementById(shuffled[1]).className ="css1";
    alert (shuffled[0] + " classname is " + document.getElementById(shuffled[0]).className); // for testing
    alert (shuffled[1] + " classname is " + document.getElementById(shuffled[1]).className); // for testing
    }
    
    function shuffle(Arr) {
    var NewArr = Arr.slice(0);  // copy the array
    var len = NewArr.length;
    while (len>0) {
    NewArr.push(NewArr.splice(Math.floor(Math.random()*len),1)[0]);
    len--;
    }
    return NewArr;
    }
    
    </script>
    
    </body>
    </html>
    At least once per year, some group of scientists will become very excited and announce that whatever they announced last year about global
    warming is wrong.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •