Algorithms, Blockchain and Cloud

JQuery Examples – Random Squares


JQuery is a must for Javascript web developers. Using JQuery, it takes less code to do powerful stuffs. The Jquery selectors are so handy that you can totally forget about the document.getElementById(), the traditional way to get DOM (Document Object Model) objects.

We are creating a demo using JQuery to create 100 random squares and fulfill them with different colors, and also resize them by random sizes every 0.1 second. First let us see the demo live at URL: https://helloacm.com/jquery-examples/random-squares/

It is mobile user friendly!

mobile-user-friendly-test-random-squares-jquery

You would need to create a div (or other HTML container) as the canvas to draw these random squares.

<div> id='canvas'> </div>

And in order to manipulate the left and top css properties, we would need to assign the css property position to value absolute.

.square {
  position: absolute;
}

And the rest of JQuery code is simple.

    $(document).ready(function() {
      const SQ_NUM = 100; // the number of squares
      for (var i = 0; i < SQ_NUM; i ++) { // create the squares
        $('#canvas').append('
'); } function get_random_color() { function c() { // get random colors return Math.floor(Math.random()*256).toString(16); } return "#"+c()+c()+c(); } setInterval(function() {// every 0.1 second for (var i = 0; i < SQ_NUM; i ++) { var obj = $('#square' + i); obj.css("outline", "1px solid " + get_random_color()); // fulfill random color obj.css("background", get_random_color()); var width = $(document).width(); var height = $(document).height(); var left = Math.floor(Math.random() * width); var top = Math.floor(Math.random() * height); // move randomly obj.css("left", left); obj.css("top", top); var min = Math.min( Math.floor(Math.random() * (width - left)), Math.floor(Math.random() * (height - top)) ); // set the size obj.css("width", min); obj.css("height", min); } }, 100); });
Just imagine that would take a lot more to code without the help of JQuery! Share on X

You might also be interested in this particular Processing JS examples:

https://helloacm.com/processing/random-shapes/

The full HTML source code is at github:

–EOF (The Ultimate Computing & Technology Blog) —

501 words
Last Post: Multilingual Bug Fix, PHP 7 and WordPress 4.4 Compatibility - WP Rocket 2.6.14
Next Post: Unblocking Document from CogniDox through WIndows 10 Edge Browser

The Permanent URL is: JQuery Examples – Random Squares (AMP Version)

Exit mobile version