n_x_l
n_x_l

Reputation: 1610

jQuery: Delay hover until second time

In my application, I have a "following" button that I display to the user once they click another button "follow", exactly like Twitter does it.

My small issue is that when the user clicks follow and I display the "following" button, it immediately changes to "Unfollow" because that's the hover event I am attaching to it. Some code to illustrate:

$('.following').hover(
  function() {
      var $this = $(this);
      $this.val("Unfollow");
  },
  function() {
      var $this = $(this);
      $this.val("Following");
  }
);

This is because when the "following" button shows up, it ends up behind the cursor, therefore triggering the hover event. What I would like to achieve is some way to delay this hover event until the mouse pointer exits the button for the first time then returns to it. This is how Twitter does it and I think it's an excellent UI improvement.

Upvotes: 1

Views: 162

Answers (2)

Elec
Elec

Reputation: 1744

    $('.follow').click(function(){          
        if($(this).attr("class") == "follow"){
            $(this).one("mouseleave",function(){
                $(this).mouseover(function(){
                    var $this = $(this);
                    $this.html("Unfollow");
                }).mouseout(function(){
                    var $this = $(this);
                    $this.html("Following");
                });
            });
        }else{
            $(this).off('mouseover mouseout');
            $(this).html('follow');
        }
        $(this).toggleClass("follow following");
    });

example:http://jsfiddle.net/z3t5r3ud/
Try this one.
I prefer to use css but maybe you have to use javascript for some reasons.

Upvotes: 1

Pixxl
Pixxl

Reputation: 996

To simulate the UI of Twitter for following/unfollowing a user, I would recommend you allow your program to know the state of the current follow. You can do this by use of a variable, or a data- attribute on your button. For my example in JSFiddle, I used a variable just to make it quicker.

>> Live Example: JSFiddle

var isFollowing = false;
$(".following").click(function(){
    if(isFollowing == false) {
        isFollowing = true;
        $(this).html("Following");
    }
    else if (isFollowing == true) {
        isFollowing = false;
        alert("unfollowing!");
        $(this).html("Follow");
    }
});

$(".following").hover(
    function() {
        if (isFollowing == true) {
            $(this).html("Unfollow");
        }
    },
    function() {
        if (isFollowing == true) {
            $(this).html("Following");
        }
    }
);

-mbp

Upvotes: 0

Related Questions