Search code examples
livejquery

Can you use jQuery .css() with .live()?


I have a div with class="centerMessage" . This div is inserted into the DOM at a point after the page is loaded. I would like to change the CSS on this div to center it. I tried the CSS function below, but it did not work. Does anybody know a way to do this?

function centerPopup() {
var winWidth = $(window).width();
var winHeight = $(window).height();
var positionLeft = (winWidth/2) - (($('.centerMessage').width())/2);
var positionTop = (winHeight/2) - (($('.centerMessage').height())/2);
$('.centerMessage').live( function(){
$(this).css("position","absolute");
$(this).css("top",positionTop + "px");
$(this).css("left",positionLeft + "px");
});
}

Solution

  • If my assumption of what you're trying to achieve is correct, you don't need any Javascript to do this. It can be achieved by some simple CSS.

    .centerMessage {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -150px; /* half of the height */
        margin-left: -300px; /* half of the width */
        width: 600px;
        height: 300px;
        background: #ccc;
    }
    

    Demo: http://jsbin.com/awuja4