HyderA
HyderA

Reputation: 21371

Simple toggleClass on click not working on table

$('td').click({
    $(this).toggleClass("selected");
    $("td .selected").toggleClass("selected");
});

I get the error: missing : after property id on both those lines.

Upvotes: 1

Views: 1144

Answers (1)

karim79
karim79

Reputation: 342635

You forgot to say 'function()' :)

$('td').click(function(){
    $(this).toggleClass("selected");
    $("td .selected").toggleClass("selected");
});

Note that you were trying to pass an anonymous function to the click event. Without the function() keyword, the interpreter choked and threw those errors. Look at it like this:

//perfectly valid, but doesn't do anything
$('td').click(function(){});

Your toggleClass statements are just arbitrary expressions within the function:

//flesh it out with some behaviour
$('td').click(function(){
    $(this).toggleClass("selected");
    $("td .selected").toggleClass("selected");
});

It's called an anonymous function because it doesn't have a name. You can pass a named function like so:

function sayHello()
{
    alert('Hello!');
}

$('td').click(sayHello);

Upvotes: 3

Related Questions