Search code examples
jquerycsseventslive

How to create live event for css


How can I make this code live?

$("#send_button").css({ opacity: 0.2 });

This code is applied on an element from inside a div on document ready. That div gets replaced by other div on an event, then It gets reinserted again dinamically with html().

This is the div (example):

<div id="dinamic_div"><img src="image.jpg" id="send_button"></div>


Solution

  • Create a CSS rule and it will apply to any object that matches the selector even if it's created dynamically.

    #send_button {opacity: 0.2;}
    

    Or, make a CSS rule with the opacity on a class name and put the class name on your button:

    .lightButton {opacity: 0.2;}
    
    <div id="dinamic_div">
        <img src="image.jpg" class="lightButton" id="send_button">
    </div>
    

    If you have to do it with javascript, then you're easiest method would be to just style the dynamic object when it's created.

    If you can't do that, you could create a CSS rule with javascript.

    Working example:

    var html = '<div id="dinamic_div"><img src="http://dummyimage.com/200x100/000/fff&text=Hello" id="send_button"></div>';
    
    $(html).appendTo(document.body);
    
    var style = document.createElement("style");
    style.type = "text/css";
    style.innerHTML = "#send_button {opacity: 0.2;}";
    document.getElementsByTagName("head")[0].appendChild(style);
    

    Working demo: http://jsfiddle.net/jfriend00/Cnbvg/