Aritra Hazra
Aritra Hazra

Reputation: 524

Not getting correct height & width of a div after creation

This is a code for notification, and I want to place it in the middle of the screen. but on first click its not in the middle, on the second click its showing as I expect. I think it's an error of hight & width.
(help without defining css)

var showNotice = function(txt,mode){

 var mode = mode || 0;
 var width = $(window).width();
 var height = $(window).height();
 $("body").append("<span id='notice'>"+txt+"</span>");
 var noticeW = $("body #notice").outerWidth();
 var noticeH = $("body #notice").outerHeight();
 $("body #notice").css({
    "position":"absolute",
    "z-index":"1000",
    "background":"black",
    "color":"white",
    "padding":"20px",
    "cursor":"pointer",
    "border-radius":"8px",
    "box-shadow":"0 0 15px rgba(0,0,0,0.6)",
    "top":(height/2)-(noticeH/2)+"px",
    "left":(width/2)-(noticeW/2)+"px",
    "display":"none"
 }).fadeIn();

 $(document).on("click","body #notice",function(){
    $("body #notice").fadeOut(1000,function(){
        $(this).remove();
    });
 });

 if(mode === 0){
    setTimeout(function(){
        $("body #notice").fadeOut(1000,function(){
            $(this).remove();
        });
    },5000);
 }

} // ----- showNotice() -----

Html

<button onclick="showNotice('some text',1)">
 Click
</button>

JSfiddle

Upvotes: 1

Views: 150

Answers (1)

Amin Jafari
Amin Jafari

Reputation: 7207

that's because by the time you're getting #notice outerHeight and outerWidth it does not have a width or height, or any other CSS style, try this: DEMO

var showNotice = function(txt,mode){
    var mode = mode || 0;
    var width = $(window).width();
    var height = $(window).height();
    $("body").append("<span id='notice'>"+txt+"</span>");
    $("body #notice").css({
        "position":"absolute",
        "z-index":"1000",
        "background":"black",
        "color":"white",
        "padding":"20px",
        "cursor":"pointer",
        "border-radius":"8px",
        "box-shadow":"0 0 15px rgba(0,0,0,0.6)"});
    var noticeW = $("body #notice").outerWidth();
    var noticeH = $("body #notice").outerHeight();
    $("body #notice").css({
        "top":(height/2)-(noticeH/2)+"px",
        "left":(width/2)-(noticeW/2)+"px",
        "display":"none"
    }).fadeIn();

Upvotes: 2

Related Questions