Kenneth Vogt
Kenneth Vogt

Reputation: 995

How do you get hover and click to play well together in jquery?

I am trying to change the style of some text when I hover in on a certain element. On hover out, I would like to change it to different text. On click, I would like to change it to a third value and not change on the hover out. On hover in, hover out, hover in, hover out, and click, it should stay the same. It all works -- except after the first click, the hover in action works fine but the hover out action never works again.

A simple application of this would be to show a "preview" on hover in but to change back on hover out if there is no click. Upon a click however, I want it to make a fixed change while not losing the hover in/hover out capability after the click.

My guess is that I have to turn the mouseleave event back on but where would I apply it and how?


Here is what I have tried so far:

HTML:

<a href="javascript{}" class="citation">click me</a>

Javascript:

var $j = jQuery.noConflict();
$j(document).ready(function()
{
    $j('.citation').hover(function(event)
    {
        $j(this).html('hover in');
        $j(this).click(function(event)
        {
            event.preventDefault();
            $j(this).html('clicked');
            $j(this).off('mouseover mouseleave');
        });
    }, function()
    {
        $j(this).html('hover out');        
    });
}); 

FIDDLE

Upvotes: 0

Views: 108

Answers (1)

Dave Anderson
Dave Anderson

Reputation: 12294

You are not binding the onclick event until you mouseover which works fine because you can't click without the mouseover event firing. In the click event you turn off both mouseover and mouseleave which removes all the hover functionality. The onclick event will still work because it is already bound but it has no further affect.

I've altered the code so it appends each event rather than setting the html so you can see what events still fire.

Here the hover out is bound only when the hover in event happens. If the click event occurs it is removed to stop it happening after the click. The next hover in will bind the event again.

var $j = jQuery.noConflict();
$j(document).ready(function()
{
    $j('.citation').on('mouseenter', function(event) {
        $j(this).append($j('<div>', { html: 'hover in' }));
        $j(this).on('mouseleave', function(event)  {
          $j(this).append($j('<div>', { html: 'hover out' }));        
        });
      }
    ).on('click', function(event) {
        event.preventDefault();
        $j(this).append($j('<div>', { html: 'clicked' }));
        $j(this).off('mouseleave'); // hover out stopped
    });
}); 

Upvotes: 1

Related Questions