$(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?
watermark. Suspect it isposition:absoluteand you haven't used adequate css and the text is overflowing the elementposition:absolutewithout enough properties to give it any width