Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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..

like image 810
dotNETbeginner Avatar asked Dec 23 '11 07:12

dotNETbeginner


2 Answers

Try:

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

And

td.focus { background-color:Blue; }

like image 90
Derk Arts Avatar answered Sep 23 '22 19:09

Derk Arts


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)

like image 31
wyqydsyq Avatar answered Sep 24 '22 19:09

wyqydsyq