Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to change the background of a html randomly and dynamically

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 129
    Comment on it

    We can change the color of the background of the body and of any part let the part be header or div. It can be anything.

    We can change the background color of the html using the jquery in our html.

    For that first of all we have to include the jquery in our html and then write the code below.

    Here i have explain two ways of doing it.

    First by using the color of your choice which can be anything and any number you want to. This is applied on the header.

    Second is the using rgb color which will be random and differentiate much.

    I have use both of them in the single function you can also take another function for each.

    The time can also be changed here this is taken 1 sec that is 1000 milliseconds.

     

    <!DOCTYPE html>
    <html>
    <head>
        <style type="text/css">
        h1{
            font-style: sans-serif;
            font-size: 18px;
        }
        div{
            height: 100px;
            width: auto;
            
        }
        </style>
        <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
        <script type="text/javascript">
            
    
    
     $(document).ready(function() {
    changecolor();
    });
    function changecolor() {
    var color = ["#00FF00", "#CCCCCC", "#990099", "#FEA400", "#FF9900", "#6600FF", "#333333" ];
    var randa = Math.floor(Math.random() * color.length);
    //You can also give specific color of your choice and do by this method.
    $('#set-background').css("background-color", color[randa]);
    
    
    var rand = 'rgb(' + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ','
                     + (Math.floor((256-199)*Math.random()) + 200) + ')';
    $('#my-element').css("background-color", rand);
    setTimeout('changecolor()', 1000);
    }
    
    
     </script>
        
    </head>
    <body>
    <h1 id="set-background">This is the title</h1>
    <div id="my-element">
        This is the body
    </div>
    </body>
    </html>

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: