IluTov
IluTov

Reputation: 6862

Issue with event functions

I have a strange issue with jQuery.

I have a function, which gets executed on an event of a <a> tag.

link.click(someAction);

In the action, I modify another div-element, where I simply set a few CSS parameters and modify the classes.

This works as expected.

Now, I wanted to expand someAction with a bool parameter.
I figured that I could call the method now as followed:

link.click(function () {
    someAction(true);
});

Unfortunately, this does not work. I have no idea why.
The method gets called and everything, but the CSS & classes simply do not change.

Then again by calling exactly the same method with link.click(someAction); it works.

Can anyone tell me why?


Here's some code

var openPopover = function( showOverlay ){
    if (typeof showOverlay === "undefined" || showOverlay === null) showOverlay = true;

    if (showOverlay) {
        // Add transparent overlay
        overlay.show();
}

    // Select popover next to the clicked item
    popover = $(this).next("div.popover");
    // It positioned underneath the clicked item, with the spacing above

    // Display the popover
    popover.show();

    // Reset classes
    popover.removeClass("hide-animation");
    popover.addClass("show-animation");

    var animationEnd = function() {         
        $(overlay).off("webkitTransitionEnd");
        $(overlay).off("oTransitionEnd");
        $(overlay).off("transitionend");
    };

    // Add animation did end observer
    $(overlay).on("webkitTransitionEnd", animationEnd);
    $(overlay).on("oTransitionEnd", animationEnd);
    $(overlay).on("transitionend", animationEnd);

    // Run animations
    popover.addClass("shown");
    overlay.addClass("shown");

    // If the browser doesn't support css3 animations, we call it manually
    if (!supportsCSSAnimations) {
        setTimeout(animationEnd, animationDuration);
    }
  };

  selectButton.hover(openPopover); // Opens the popover correctly

  selectButton.hover(function () {
    openPopover(true); // Doesn't work
  });

Upvotes: 0

Views: 64

Answers (2)

Yoshi
Yoshi

Reputation: 54649

After your changes:

this in the following line, will point to window:

popover = $(this).next("div.popover");

whereas before, it pointed to selectButton. Try:

selectButton.hover(function () {
  openPopover.call(this, true);
});

Upvotes: 1

istos
istos

Reputation: 2662

Make sure to preventDefault on the link once it has been clicked:

link.click(function (e) {
    e.preventDefault();
    someAction(true);
});

Upvotes: 0

Related Questions