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?

r1987
  • 507
  • 1
  • 7
  • 21

3 Answers3

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.

cfs
  • 10,610
  • 3
  • 30
  • 43
  • 1
    that's it, but also add a `e.stopPropagation()` to prevent the crazyness. [Fiddle here](http://jsfiddle.net/techunter/5CMCH/4/) – TecHunter May 29 '13 at 12:34
  • OK. this makes sense, but it only triggers it once, if id like to shuffle it again, i'd have to refresh the page. I'd like to do it like: in, out, in out … and everytime it changes. I tried Klasman's answer, it kindof worked, but the inline-block makes a mess out of the page, when I hover on the header in and out. – r1987 May 29 '13 at 12:52
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.

CBroe
  • 91,630
  • 14
  • 92
  • 150
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/

klaasman
  • 856
  • 7
  • 15