MindX
MindX

Reputation: 49

How to apply effect of one function for each class?

I have this code made to shuffle characters randomly and create an hover effect. I'm using it for a navigation. But it appears that my code works only for a single class and when I put multiple classes it breaks everything and generate a shuffle for everything at the same time, indefinitly ....

BEWARE : use the snippet with caution it can make your navigator crashed...

// Shuffle
jQuery(function($) {
    function text_shuffle() {
        "use strict";
        var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*?><[]&@#)(.%$-_:/;?!";
         $_inter = setInterval(function() {
            var text = $(".text-shuffle").text();
            text = text.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.substring(counter+1);
            $(".text-shuffle").text(text);
            counter = (counter+1)%text.length;
        }, 150);
    }
    var value, $_inter;

    $(".text-shuffle").mouseenter( function(){
        value  = $(this).html();
        text_shuffle();
    }).
    mouseout(function(){
        clearInterval($_inter);
        $(this).html(value);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="text-shuffle">Title 1</div>

<div class="text-shuffle">Title 2</div>

<div class="text-shuffle">Title 3</div>

Upvotes: 1

Views: 33

Answers (1)

technophobia
technophobia

Reputation: 2629

If you pass the current element to the function, you can limit the scope like this:

// Shuffle
jQuery(function($) {
    function text_shuffle($element) {
        "use strict";
        var counter = 0, all = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*?><[]&@#)(.%$-_:/;?!";
         $_inter = setInterval(function() {
            var text = $element.text();
            text = text.substring(0, counter) + all.charAt(Math.floor(Math.random()*all.length)) + text.substring(counter+1);
            $element.text(text);
            counter = (counter+1)%text.length;
        }, 150);
    }
    var value, $_inter;

    $(".text-shuffle").mouseenter( function(){
        value  = $(this).html();
        text_shuffle($(this));
    }).
    mouseout(function(){
        clearInterval($_inter);
        $(this).html(value);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<div class="text-shuffle">Title 1</div>

<div class="text-shuffle">Title 2</div>

<div class="text-shuffle">Title 3</div>

Upvotes: 4

Related Questions