user1023465 user1023465 - 6 months ago 8
jQuery Question

jQuery width function returning 0 on text



$(window).load(function() {
$("img").each(function() {
$(this).after("<div id='watermark'>Hello</div>");
var width = $('#watermark').eq(0).width();
//This outputs 0s
console.log(width);
$("#watermark").css("margin-left", "-" + width.toString() + "px");
});


$("img").click(function() {
setTimeout(function() {
$("img").each(function() {
//this outputs 37
console.log($('#watermark').eq(0).width());
$(this).after("<div id='watermark'>Hello</div>");
});
}, 500);
});

});





I am trying to get the width of the watermark I insert over images so that I can center the watermark by subtracting half the width from the left margin. However, for some reason, I am getting 0s from the .width() function even though I know that the div exists because I had already inserted the div in the previous line. Also, in the second part of the code, you'll see that when the image is clicked, the width is returned properly. Why am I getting 0s in the first half?

Edit: Here is the CSS on Watermark:



#watermark {
opacity: 0.5;
z-index: 99;
position: absolute;
color: white;
top: 50%;
left: 50%;
text-align: center;
}





Is position: absolute causing a problem?

Answer

Based on css update an absolute position element has no width unless you either declare width or set both left and right.

In your css rule try including either width:100% or right:0 and then run your code and you will have some width value