Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery bind click and hover, how to check if click

I have combined function like this(simplified version):

$('label').bind('click hover', function() {
    $('label').removeClass("active");
    $(this).addClass("active");
});

How can I add an if to check if it is a click?

like image 558
John Magnolia Avatar asked Mar 21 '12 22:03

John Magnolia


People also ask

How do you check if the element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

How do you click on hover?

You can click or drag simply by hovering your mouse pointer over a control or object on the screen. This is useful if you find it difficult to move the mouse and click at the same time. This feature is called Hover Click or Dwell Click.

How will you check if an element is hovered or not using CSS?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery. The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.


1 Answers

Use event.type:

$('label').bind('click hover', function(event) {
    if(event.type == 'click') {
        // do stuff
    }
    $('label').removeClass("active");
    $(this).addClass("active");
});

Demo: http://jsfiddle.net/jtbowden/sqvDy/

Note, the demo uses .on(), which is the new method of event binding for jQuery 1.7+, replacing .bind(), .live(), and .delegate().

like image 124
Jeff B Avatar answered Oct 21 '22 21:10

Jeff B