Question

This works:

$("a.hover").hover(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

This doesn't:

$("a.click").click(function (){
        $(this).css("text-decoration", "underline");
    },function(){
        $(this).css("text-decoration", "none");
    }
);

I understand it may not be designed to work like this, but why not?

I'm also not entirely sure what having the second function after the comma actually does. I have only ever written it like this:

$("a.click").click(function (){
        $(this).css("text-decoration", "underline");
    });

http://jsfiddle.net/tmyie/4DygF/7/

Any clarification would be great.

No correct solution

OTHER TIPS

The .click() register's a click handler to the target set of elements, the hover() is a shortcut to register the mouseenter and mouseleave handlers.

hover:

Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

.click() also had a similar short using .toggle() but it was removed in jQuery 1.9.

For now if you want the same functionality you can look at this toggleClick() implemetation

.hover() takes two callbacks - one for hovering in and one for hovering out. .click() should only be given one callback. Since you're giving it two, it's actually thinking the second one is the click callback.

The definition of the jQuery click event, as shown at http://api.jquery.com/click/ is:

.click( handler(eventObject) )

It takes one parameter, that is the function to execute when the click event has been fired. In your example you provide two functions as parameter to the click function. Therefore this is not going to work.

for the click you can use if/else like so: because Click event have 1 callback function

    var state=0;
    click(function(){
    if(state==0){
    //do this
    state=1;
    }
else{
    //do this
    state=0;
    }
    });

That's because with .hover you can add two handlers (handlerIn, handlerOut), but .click only have one handler

If you want click to behave like toggle.Try this:

var a=1;
$("a.click").click(function (){
if(a==1){
    $(this).css("text-decoration", "underline");
    a=0;
}else{
    $(this).css("text-decoration", "none");
    a=1;
}
});

Demo

You can make it work by doing something like this:

// listen for a.click to be clicked within the scope of the body
$('body').on('click', 'a.click', function(e){

    // prevent the click from registering
    e.preventDefault();

    // check if text-decoration is an underline
    if($(this).css('text-decoration').substring(0, 9) == 'underline'){
        // set it to nothing
        $(this).css('text-decoration', 'none');
    }
    else{
        // set it to underline
        $(this).css('text-decoration', 'underline');
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top