Randomly Shuffle Positions of Elements

Home Forums FAQ / Tips Randomly Shuffle Positions of Elements

This topic contains 0 replies, has 1 voice, and was last updated by  EdwinGom 9 months, 4 weeks ago.

Viewing 1 post (of 1 total)
  • Author
    Posts
  • #1594
    Jeremy
    Jeremy
    Keymaster

    Say you want to show three elements in line on the screen, but randomly determine which one appears to the left, to the right or in the middle. What you need to do is group them within a Selector element and use its command shuffle:

    newCanvas("green", 100, 100)
        .settings.css("background", "green")
    ,
    newCanvas("red", 100, 100)
        .settings.css("background", "red")
    ,
    newCanvas("blue", 100, 100)
        .settings.css("background", "blue")
    ,
    getCanvas("green")
        .settings.after(
            getCanvas("red")
                .settings.after( getCanvas("blue") )
        )
        .print()
    ,
    newSelector("canvas")
        .settings.add( getCanvas("green") , getCanvas("red") , getCanvas("blue") )
        .settings.disableClicks()
        .shuffle()
    

    If you want to later check the result positions of the elements, you can use the test command index on the Selector element. In the example above green, red and blue are initially added to the selector with indices 0, 1 and 2 respectively (i.e., the order in which they appear in add) and initially appear in this order from left to right, so you know that whichever element ends up with index 0 after the shuffle is the left-most element and 2 is the right-most element.

Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.