unidentified-1
unidentified-1

Reputation: 131

jQuery function only works once

I've set up a function which I want to use in multiple ways around the webpage.

In the example there are two buttons/triggers. One trigger is a class, the other an id. The OverActivate (class) rollover, should make .cycle1 and .cycle2 start playing. The OverDrive (id) rollover, should make .cycle3 start playing.

In the given example, the function is called three times. 1. It only runs once. 2. It gets mixed up between one trigger and the other.

The mix of id's and classes is not an issue, I've tested it. The problem appears to lie in this function/loop...

function player() {
    int = setInterval(function(){
        id.eq(i % l);
        i++;
        id.hide().eq(i % l).show();
    }, $speed );
}

but I can not figure out why.

Any help would be much appreciated.

The fiddle:

http://jsfiddle.net/HRPLS/1/

jQuery Code:

function mh2($id,$trigger,$speed){
    id = $($id), l = id.length, i = 0;
    id.css({ 'display':'none' });
    $($id+':eq(0)').css({ 'display':'inline' });

var int;
function player() {
    int = setInterval(function(){
        id.eq(i % l); i++; id.hide().eq(i % l).show(); },
        $speed );
    }

$($trigger).mouseenter(function(){
    clearInterval(int);
    player();
}).mouseleave(function(){
    clearInterval(int);
});
}

mh2('.cycle1','.switch',700);
mh2('.cycle2','.switch',500);
mh2('.cycle3','#switch2',300);

Example HTML:

<style>
.switch, #switch2 {
    display:block; padding:10px; color:#fff; background:#888;
}
.switch:hover {
    cursor:pointer; color:#8f8; background:#080;
}
#switch2:hover {
    cursor:pointer; color:#f88; background:#800;
}
.cycle1, .cycle2, .cycle3 {
    border:1px solid #999; max-width:200px; max-height:200px; margin:20px;
}
</style>

<div class="switch">OverActivate</div>

<img src="car1.jpg" class="cycle1">
<img src="car2.jpg" class="cycle1">
<img src="car3.jpg" class="cycle1">
<img src="car4.jpg" class="cycle1">

<img src="tire1.jpg" class="cycle2">
<img src="tire2.jpg" class="cycle2">
<img src="tire3.jpg" class="cycle2">
<img src="tire4.jpg" class="cycle2">

<hr>

<div id="switch2">OverDrive</div>

<img src="bike1.jpg" class="cycle3">
<img src="bike2.jpg" class="cycle3">
<img src="bike3.jpg" class="cycle3">
<img src="bike4.jpg" class="cycle3">

Upvotes: 1

Views: 339

Answers (1)

Barmar
Barmar

Reputation: 780688

You need to declare the variables id, l, and i with var so that each call to mh2() will create closures over those variables. Without this, they're global variables, and they just contain the values from the last call to mh2().

function mh2($id, $trigger, $speed) {
    var id = $($id),  l = id.length,  i = 0;
    ...
}

Corrected fiddle

See also: How do JavaScript closures work?

Upvotes: 1

Related Questions