2

I have:

<img id="leftBubble" class="bubbles" src="left.png" />
<img id="rightBubble" class="bubbles" src="right.png" />

And a hover event like so:

$(".bubbles").each(function(){
    $(this).hover(function() { 
        pause($(this));
    }, function() {
        play(4000, $(this));
    });
});

My pause() function does not seem to be working

function pause(pauseMe) {
    if (pauseMe == $("#leftBubble")) {
        clearTimeout(timer1);                        //this is never reached
    } else if (pauseMe == $("#rightBubble")) {
        clearTimeout(timer2);                        //nor this
    }
}

Any idea to make the hover event pass $this as the parameter for the pause function?

jaredrada
  • 1,130
  • 3
  • 12
  • 25
  • jquery equality is best done with `.is("selector")`: see http://stackoverflow.com/questions/2448291/how-to-check-for-dom-equality-with-jquery/2448362#2448362 – Andras Zoltan Apr 17 '12 at 20:41
  • compare jquery object :http://stackoverflow.com/questions/2436966/how-would-you-compare-jquery-objects – malletjo Apr 17 '12 at 20:42

4 Answers4

4

Each time you call $, it returns a different result set object, even if the result contents are the same. The check you have to do is:

if (pauseMe.is("#leftBubble")) {
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
4

Try like below,

function pause(pauseMe) {
    if (pauseMe == "leftBubble") {
        clearTimeout(timer1);
    } else if (pauseMe == "rightBubble") {
        clearTimeout(timer2);
    }
}

and in the caller,

$(".bubbles").each(function(){
  $(this).hover(function() { 
    pause(this.id);
  }, function() {
    play(4000, $(this));
  });
});
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

In javascript, this is redefined each time you enter a new function definition. If you want to access the outside this, you need to keep a reference to it in a variable (I used the self) variable.

$(".bubbles").each(function(){
    var self = this;
    $(this).hover(function() { 
        pause($(self));
    }, function() {
        play(4000, $(self));
    });
});

I don't know if your comparison between jQuery objects will work though. Maybe you can compare the DOM elements: pauseMe[0] == $("#leftBubble")[0], or, as mentioned, the ids.

  • 1
    In this case the outside `this` and the inside `this` will be the same. –  Apr 17 '12 at 20:45
0

When you call $( ... ) it generates new object that not the same that was genereted when you call $( ... ) last time, with same parametrs.

Anyway, you can't compare objects with == in javascript. It returns true only if it liks on same object.

a = {b:1}
c = {b:1}
d = c

a == b // false
d == c // true
Roman Pominov
  • 1,403
  • 1
  • 12
  • 17