Max Krizh
Max Krizh

Reputation: 595

jQuery: simple animation using :hover

I have four squares on the page. All of them have :hover pseudo-class with the transition, that will add an inset shadow in 0.5 seconds on hovering.

What I need to do is to write a jQuery code that smoothly and randomly will simulate :hover state on the page load.

Sorry for a bit unclear explanation. So, when the page is loaded, jQuery would add a shadow to one square, then remove it in some time and then will do the same procedure with other squares in a random-order.

That's my code here: http://jsfiddle.net/bqux7/

With best regards

Upvotes: 1

Views: 108

Answers (2)

azzy81
azzy81

Reputation: 2269

Ive had a go in this fiddle. It seems to work well have a look ad see what you think: http://jsfiddle.net/bqux7/4/

I added a class .hover to do the transistion and added the following jquery:

$(function() {

    var myArray = ['#s1', '#s2', '#s3', '#s4'];

    window.setInterval(function(){
        doHover();   
    }, 2000);

    function doHover(){
        var rand = myArray[Math.floor(Math.random() * myArray.length)];
        for(i in myArray){
            $(myArray[i]).removeClass("hover");    
        }

        $(rand).addClass("hover");      
    }

    doHover();

})

You'll need some additional code to stop the hover affect when someone actually hover over the squares I reckon.

Upvotes: 1

Maen
Maen

Reputation: 10698

You can proceed as this :

1- Copy-paste your :hover CSS code in another class, say .hovered.

2- Optional : Add a class to your s# elements, like .squares

3- Add your elements in an array :

//If you don't will to put a class
var arrayOfSquares = [$('s1'),$('s2'),$('s3'),$('s4')];
//If you do, it's cleaner
var arrayOfSquares = $('.squares'); 

4- Place a timer in your JS, and you'll use Math.random and Math.floor to take a random element from your array :

//Every 8 seconds, call this code :
window.setInterval(function() {
    var index = Math.floor(Math.random() * arrayOfSquares.length); //Take a number between 0 and your number of elements
    var currentSquare = $(arrayOfSquares[index]); //Get your jQuery DOM element

    //Add the class, wait 2 seconds, then remove it
    currentSquare.addClass('hovered').delay(2000).removeClass('hovered');

}, 8000);

Reference for setInterval

Upvotes: 1

Related Questions