1

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

1
  • 1
    Adding your code would help. Commented Nov 15, 2013 at 12:16

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.