How would i apply css style s to the dynamically created table element?? tblResult is a dynamic table i am creating .
<script type="text/javascript">
$(document).ready(function () {
$('#tblResult tbody tr').on('mouseover', function () {
$(this).addClass('highlightRow');
});
});
Is It true that .addClass will not work with the dynamic controls in jquery?
Suppose If i want to add class to child element:
$('body').on('mouseover', '#tblResult tbody tr td #im', function () {
$(this).addClass('transition');
});
Is that ok??
To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element. Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically.
Apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here you can pass key as property and val as its value as described above.
As replied below, there are two solutions: (1) remove the curly brace and change backgroundColor to background-color (css class) or - the core problem) put the missing curly brase at the end and use the DOM/JS notation witch also works. THANKS EVERYONE!
Use the css() function to apply style to existing elements where you pass an object containing styles : var styles = { backgroundColor : "#ddd", fontWeight: "" }; $("#myId"). css(styles);
Since your table have been added dynamically to the DOM, all the events will not be available to this table and elements such as <tr>
or <td>
inside it. In this case, you need to use event delegation:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
$(document).ready(function () {
$('body').on('mouseover','#tblResult tbody tr',function() {
$(this).addClass('highlightRow');
});
});
So basically, event delegation will help you to attach mouseover
event to these newly created <tr>
elements in this case.
Why don't you apply the css for the tr directly in css instead of adding an event?
tr:hover{
background-color: #BADA55;
}
check out the fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With