views:

48

answers:

1

I'm using jQuery CSS function to style some elements

$element.css(style);

This works, but a part of the elements are created dynamically after the page load. This should be

$element.live ('created',function() {
$(this).css(style);
});

I'm stuck on the created event. Any ideas?

+3  A: 

There's no event for elements created (not universally available, anyway). You could

  • Add the rules to a stylesheet so that they are automatically applied to the newly created elements
  • Chain the css() method when you create your elements:

    $('<img id="createdImage" src="some.jpg"/>')
        .appendTo(document.body)
        .css(style);
    
  • Create a new stylesheet dynamically:

    $("<style>").text("#myNewEl { width:20px; height:30px; }").appendTo("head");
    
Andy E
I was using a stylesheet and what I wanted to do is to get rid of it (less files) and use CSS since its inline CSS.
Omar Abid
@Omar inline CSS is a very bad idea in general. There's nothing wrong with having one CSS file with your styles in. In fact it's beneficial because users will download it once and it should be cached on subsequent page views. Although I should say, inline CSS is fine when you need to do it dynamically, e.g. you don't know the required width/height of an element ahead of time.
DisgruntledGoat