Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply css on dynamic controls in jquery

Tags:

jquery

css

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

like image 865
Aj_sari Avatar asked Mar 31 '14 05:03

Aj_sari


People also ask

How to set css in jQuery dynamically?

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.

How to add Multiple css dynamically in jQuery?

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.

How to apply css to element using jQuery?

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!

How to add dynamic css?

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);


2 Answers

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.

like image 139
Felix Avatar answered Oct 22 '22 09:10

Felix


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

like image 21
Lee Gary Avatar answered Oct 22 '22 07:10

Lee Gary