- Highlighting the selected row in a table
- 4 Answers 4
- HTML
- JS
- DEMO
- DEMO
- Related
- Hot Network Questions
- Subscribe to RSS
- Highlight the row of a table on mouseover using Javascript and CSS
- 3 Answers 3
- Подсветка строк в таблице по клику и при наведении курсора мышки
- Highlight rows in HTML table (hovered over row and preceding rows)
- Javascript to Highlight Table Row Only When inside ‘a’ tag is clicked
Highlighting the selected row in a table
Each row having a dynamic id ,Here is my question I want highlight the current row of the table which button been pressed. How can I achieve it?
4 Answers 4
A good approach will be is to change your markup like
data data data
$('#mytable button').click(function()< $('#mytable tr.highlight').removeClass('highlight'); $(this).closest('tr').addClass('highlight'); someFucntion(); >)
Onclick is outdated and is a very bad practice.. Add a class / id to selector..
$('body').on("click", ".clickMe", function()< var that = this; that.closest("tr").addClass("highlightMe"); >);
If your table is being generated dynamically or rows are being added on the go, you should watch the new dynamic elements as well..
HTML
JS
DEMO
If you want to use «best practice», remove all inline handlers. Try this:
$("button.someClass").click(function () < $("tr.highLightClass").removeClass("highLightClass"); // remove class if it is having someone $(this).closest("tr").addClass("highLightClass"); // here selected row >);
DEMO
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43537
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Highlight the row of a table on mouseover using Javascript and CSS
Below is are the functions I’m using in order to highlight a row being hovered over. I am having trouble understanding how this can be achieved when my goal is to select the tbodies from the stripe_table class. Once this is set as the event listener, I need to have the a and td nodeNames respond to the mouseover event and thus highlight their parent row. Can someone explain the steps that would allow this to be accomplished? How would I traverse the DOM from the hovered a or td element to find its parent row? Thanks! Set tbody as eventlistener on mouseover and mouseout reacts to a and td elements—>modifies tr —find the target element’s ancestor table row —so that you apply the highlighting to that table row —To traverse the DOM run a loop that resets the event —target element to its parent node until the node name of the —parent is equal to On mouseout event, need to restore the formatting*/
//Set up Hover Events function addEvent( obj, type, fn ) < if ( obj.attachEvent ) < obj['e'+type+fn] = fn; obj[type+fn] = function()obj.attachEvent( 'on'+type, obj[type+fn] ); > else obj.addEventListener(type, fn, false); > function setUpFieldEvents() < var stripeTables = document.getElementsByClassName("stripe_table"); var tableBodies = stripeTables.tBodies; addEvent(tableBodies, "mouseover", hoverHighlight); addEvent(tableBodies, "mouseout", undoHighlight); >function hoverHighlight() < var stripeTables = document.getElementsByClassName("stripe_table"); var tableBodies = stripeTables.tBodies; var tableData = tableBodies.getElementsByTagName("td"); >function undoHighlight()
3 Answers 3
Have you tried just using the CSS e.g.
If you want to use jQuery, there’s a pretty decent walkthrough here, if you want pure JS- take a look here under the section ‘Using Mouse Event Handler and Row Detection’
@meisterburger You shouldn’t use JavaScript unless you really need to. Try practicing it doing something which cannot be achieved using CSS.
Подсветка строк в таблице по клику
и при наведении курсора мышки
Представляем Вам очень красивый JavaScript код, который осуществляет подсветку строк таблицы, находящихся в данный момент под курсором мышки. При клике по какой-либо строке таблицы, данная строка будет выделена заданным цветом. При повторном клике по выделенной строке, выделение цветом пропадет.
Обратите внимание на таблицу, расположенную чуть ниже. Попробуйте навести на данную таблицу курсор мышки и покликайте по строкам данной таблицы.
1) | Значение 1 | Значение 2 |
---|---|---|
2) | Значение 3 | Значение 4 |
3) | Значение 5 | Значение 6 |
4) | Значение 7 | Значение 8 |
Согласитесь, что данная таблица смотрится довольно таки эффектно. Выделение строк по клику может пригодиться в тех случаях, когда пользователь сравнивает несколько длинных строк в таблице.
Для того чтобы получить подобную таблицу с подсвечивающими строками, для начала вставьте на своем сайте между тегами и следующий код:
Далее в тело странички необходимо добавить JavaScript код, который и будет подсвечивать необходимые строки. Для этого просто скопируйте ниже приведенный код на свою страничку.
< script type = "text/javascript" >
function highlight_Table_Rows ( table_Id , hover_Class , click_Class , multiple ) var table = document . getElementById ( table_Id );
if ( typeof multiple == ‘undefined’ ) multiple = true ;
if ( hover_Class ) var hover_Class_Reg = new RegExp ( «\\b» + hover_Class + «\\b» );
table . onmouseover = table . onmouseout = function( e ) if (! e ) e = window . event ;
var elem = e . target || e . srcElement ;
while (! elem . tagName || ! elem . tagName . match (/ td | th | table / i ))
elem = elem . parentNode ;
if ( elem . parentNode . tagName == ‘TR’ &&
elem . parentNode . parentNode . tagName == ‘TBODY’ ) var row = elem . parentNode ;
if (! row . getAttribute ( ‘clicked_Row’ ))
row . className = e . type == «mouseover» ? row . className +
» » + hover_Class : row . className . replace ( hover_Class_Reg , » » );
>
>;
>
if ( click_Class ) table . onclick = function( e ) if (! e ) e = window . event ;
var elem = e . target || e . srcElement ;
while (! elem . tagName || ! elem . tagName . match (/ td | th | table / i ))
elem = elem . parentNode ;
if ( row . getAttribute ( ‘clicked_Row’ )) row . removeAttribute ( ‘clicked_Row’ );
row . className = row . className . replace ( click_Class_Reg , «» );
row . className += » » + hover_Class ;
>
else if ( hover_Class ) row . className = row . className . replace ( hover_Class_Reg , «» );
row . className += » » + click_Class ;
row . setAttribute ( ‘clicked_Row’ , true );
if (! multiple ) var lastRowI = table . getAttribute ( «last_Clicked_Row» );
if ( lastRowI !== null && lastRowI !== » && row . sectionRowIndex != lastRowI ) var lastRow = table . tBodies [ 0 ]. rows [ lastRowI ];
lastRow . className = lastRow . className . replace ( click_Class_Reg , «» );
lastRow . removeAttribute ( ‘clicked_Row’ );
>
>
table . setAttribute ( «last_Clicked_Row» , row . sectionRowIndex );
>
>
>;
>
Далее в том месте, где должна располагаться Ваша табличка (которую мы будем разукрашивать) создаем таблицу следующим образом:
Далее остается только активировать нашу функцию highlight_Table_Rows (описанную ранее), которая и будет делать всю работу по подсветку строк таблицы. Делается это следующим образом:
В результате у Вас на сайте должна появиться точно такая же табличка с подсвечивающимися строками, как и в нашем примере, показанном выше.
Highlight rows in HTML table (hovered over row and preceding rows)
Basically, you could see the thing the opposite way : any tr after hovered tr should have no background: test this :
table:hover tr < background:gray; >table:hover tr:hover ~tr
BEWARE :This option doesn’t allow to click in cells but last one of each row.
@GCyrillus It supports most browsers very well (unless you’re still supporting IE6): reference.sitepoint.com/css/generalsiblingselector
$('tr').hover( function()< $(this).addClass('hover').prevAll().addClass('hover'); >, function() < $(this).removeClass('hover').prevAll().removeClass('hover'); >)
Since there is not previous selector, you need to sort of do the opposite. Add a hove to the tbody and chnage the color of the rows after the row that was chosen.
Head 1 Head 2 Data 1 Data 2 Data 3 Data 4 Data 5 Data 6 Data 7 Data 8
.hovTable, tr, td, th < border-collapse: collapse; border: 1px solid black; >.hovTable tbody td < background-color: #FFF; >.hovTable tbody:hover td < background-color: #CCC; >.hovTable tbody:hover tr:hover ~ tr td
var nameOfRows = "row" //useful when there are other tables in your document. //use like this // //.. . . var backgroundOriginal = "#ffffff"; //background when the row isn't selected var backgroundHover = "#ff0000"; //background when the row is selected; function setHigh (id) < var rows = document.getElementsByName(nameOfRows); for (var i = 0; i < rows.length; i++) < rows[i].style.background = backgroundOriginal; >for (i = 0; i > for (var i = 0; i
Try this out. I’ve not tested it yet, but I think it should work!
Javascript to Highlight Table Row Only When inside ‘a’ tag is clicked
I currently have a html table (with 2 columns) and I am trying to add various effects to this table such as table row hover effect, table click effect, etc. This is the script I am using now and its working fine so far:
Movie Part 1 01:23:26 Movie Part 1 01:23:26
From the above template, you can see that I am having 2 columns for this table and 1 columns has the tag with the href link and the other column doesnt have any tag. Like I mentioned above, the script I am using to highlight the table row when clicked works. But I am trying to slightly modify the script so that it only execute the click effect only when the «a» tag inside the «tr td» is clicked. Right now, the table row is highlighted doesnt matter where I click inside the ‘tr’ area. It also highlights even if I click the second column inside the ‘tr’ which has no link. How can I modify this above script so it highlights the entire table row ONLY when the ‘a’ tag inside the table row’s first column is clicked?