1

I'm creating a sort of a animated header for my homepage where I want the words to hover and change their horizontal location randomly.

HTML

<header>
  <a href="#">
    <span>One</span> <span>100</span> <span>Twenty</span> <span>2000</span>
  </a>
</header>

jQuery

(function($){

 $.fn.shuffle = function() {

    var allElems = this.get(),
        getRandom = function(max) {
            return Math.floor(Math.random() * max);
        },
        shuffled = $.map(allElems, function(){
            var random = getRandom(allElems.length),
                randEl = $(allElems[random]).clone(true)[0];
            allElems.splice(random, 1);
            return randEl;
       });

    this.each(function(i){
        $(this).replaceWith($(shuffled[i]));
    });

    return $(shuffled);

};

})(jQuery);


$("header").mouseenter(function(){

     $('span').shuffle();

});

I got this random shuffle code from css-tricks.com ands its a bit quirky. When I hover on the header it goes a little too crazy with the shuffleing and when i want to click on the link it somehow triggers the function again:

jsFiddle http://jsfiddle.net/5CMCH/1/

What I want to achieve is to have only one change when I mouseenter it, click on the link to get to the index, and another one when I mouseenter again etc.

Any hints?

4

3 回答 3

4

You can use the one function, it fires an event only once and then removes the handler:

$("header").one('mouseenter', function(e){
    e.stopPropagation()
    $('span').shuffle();
});

Updated version of your fiddle.

于 2013-05-29T12:29:48.753 回答
1

When I hover on the header it goes a little too crazy

That's because the event gets fired for the span elements as well.

Check if the event.currentTarget is your header element, and only shuffle the spans then.

于 2013-05-29T12:33:33.530 回答
0

Your javascript seems to be fine; Looks like the event is getting triggered a lot of times because the region of the a-tag changes during the shuffle. You can try to add some styling to the a-tag, like padding:

http://jsfiddle.net/5CMCH/2/

于 2013-05-29T12:34:36.707 回答