techBeginner
techBeginner

Reputation: 3850

focus a table cell on click - jquery

I have an HTML table,

when any cell is clicked, I want to highlight that cell using css, until another cell is clicked

I thought, I will set focus for that cell and set css for focus

but its not working..

my code goes as below:

$('td').click(function (event) {
    //$(this).tabindex = 0; 
    //$(this).tabindex = 1;
    $(this).focus();
});

and css as follows

td:focus
{
    background-color:Blue;
}

I think, I can't add class to td because when other cell clicked I have to remove this class then..

Please help me achieve my requirement.

Also please let me know if there is any other way of achieving this or any work arounds..

Upvotes: 5

Views: 16757

Answers (3)

Richard Logwood
Richard Logwood

Reputation: 3273

if you want to keep them "focused" until you click again you could use the handy toggleClass function

see fiddle example here: http://jsfiddle.net/eVS9f/5/

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

Upvotes: 1

wyqydsyq
wyqydsyq

Reputation: 2020

For starters, :focus is used for form input fields, I doubt it can be applied to any other elements. You should use your own class:

JS:

$('td').click(function (event) {
    $('*').removeClass('focus');
    $(this).addClass('focus');
});

CSS:

td.focus {
    background-color:Blue;
}

This way focusing a td will unfocus anything else that might have the .focus class, then set it on the selected element.

You could also do:

$('*').click(function(event){
    $(this).removeClass('focus');
});
$('td').click(function (event) {
    $(this).addClass('focus');
});

So clicking on anything will un-focus a focused td (similar behaviour to how :focus works on input fields or how :active works on anchor tags)

Upvotes: 2

Derk Arts
Derk Arts

Reputation: 3460

Try:

$('td').click(function (event) {
      $('td').removeClass('focus'); //Remove focus from other TDs
     $(this).addClass('focus');
});

And

td.focus { background-color:Blue; }

Upvotes: 11

Related Questions