Search code examples
jqueryrandomeffectsrollover

How to randomise and mimic a rollover in jquery?


I have a JQuery script which acts as a simple image rollover with a nice fade effect.

Here is a test version of the current script in action - http://fi-testing.co.uk/SO/rubix-cube.html

As you can see, there are 9 blocks, the client wishes for the rollovers to occur randomly (without a hover) to kind of create a ripple/pulsating effect.

How would this be achieved with either JQuery or php?, and would It be possible that hovering over breaks the randomisation and acts as normal?

Sorry if any of this is unclear.

Thanks for any help.

Dan


Solution

  • Without going too much into your code, you can create randomness by Math.random()

    so if you have an array of your cube entires, indexed 0 - 8, you may use

    var randomNumber = parseInt( Math.random() * 9 );
    var randomCube = cubes[randomNumber];
    

    you can use setInterval to get this to repeat once in every x ms

    function randomlyChangeCubes() { ... }
    
    ...
    
    setInterval( randomlyChangeCubes, 2000 );
    

    you can use jQuery trigger to invoke the hover effect manually, but I'd say it'd be more readable to extract the code you have in hover to a function which you call both from hover and from randomlyChangeCubes.

    All that being said... doing this entirely randomly probably won't make it look rippling/pulsating...