Focus table cell on click - jquery

I have an HTML table,

when any cell is clicked, I want to select that cell with css until another cell is clicked

I thought I would set focus on this cell and put css for focus

but its not working.

my code is as follows:

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

and css as follows

 td:focus { background-color:Blue; } 

I think I cannot add a class to td , because when another cell is clicked, I need to delete this class, then ..

Please help me achieve my requirement.

Also, please let me know if there is another way to achieve this or any work around.

+4
source share
3 answers

Try:

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

and

td.focus {background color: blue; }

+9
source

To begin with :focus used for input form fields, I doubt that 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; } 

Thus, focusing a td will defocus everything that the .focus class can have, and then set it to the selected element.

You can also do:

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

Thus, clicking on something will turn off td focusing (similar behavior with respect to how: focus works on input fields or how: active works on anchor tags)

+1
source

if you want them to โ€œfocusโ€ until you press again, you can use the convenient toggleClass function

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

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

Source: https://habr.com/ru/post/1387697/


All Articles