0

I am using the following Javscript to change table data element ID on mouse over so that I can apply different CSS on the mouse action. It is working fine, but only on the first row of my table. Does anyone know how I can amend the script so that it is applied to each individual row in my table?

$('#tdcns').mouseover(function(){
$(this).attr('id', 'hovertdcns');
});
$('#tdcns').mouseout(function(){
$(this).attr('id', 'tdcns');
});

Any guidance is much appreciated!

cr1
  • 199
  • 2
  • 16
  • Could you please provide html as well? – Naga Sai A Mar 14 '18 at 20:13
  • 3
    First, I'm guessing that you have multiple elements with the same `tdcns` id? If so, you need to change those to a `class`. Second, you can do this without JS and definitely without jQuery. CSS can handle style changes on hover. –  Mar 14 '18 at 20:13
  • I am usng django_tables2 so the html is just: {% render_table table %}. The column in the table is defined as: cns = tables.Column(attrs={'th': {'id': 'thcns'}, 'td': {'id': 'tdcns'}}) – cr1 Mar 14 '18 at 20:15
  • doodle meister, i tried various attempts at CSS through information found on SO but couldnt get it working. Do you have an example of CSS for this functionality? – cr1 Mar 14 '18 at 20:18
  • Sure just add this to your CSS for a basic example `tr:hover { background: orange; }` ...and adjust it as needed. –  Mar 14 '18 at 20:19
  • I posted an answer below showing how. –  Mar 14 '18 at 20:25

2 Answers2

1

Same Ids on multiple objects is the problem. Avoid that! If u use classes for JQuery selection, it will work as expected.

My Example works. You should consider changing styling to base on classes also.

$('.test').mouseover(function(){
$(this).attr('id', 'testhover');
});
$('.test').mouseout(function(){
$(this).attr('id', 'test');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Hallo</div>
<div class="test">Welt</div>
<div class="test">Ein</div>
<div class="test">Element</div>
David Ibl
  • 901
  • 5
  • 13
1

As noted in my comment, your IDs should be unique. However, this is better implemented without JS, but rather with CSS.

tr {
  font-size: 2em;
}
tr:hover {
  background: orange;
}
<table>
  <tr><td>foo
  <tr><td>bar
  <tr><td>baz
  <tr><td>yaz
</table>