Reputation: 794
I want to add text dynamically on an image. I tried to use javascript / jQuery to do so. Here is the code :
$(document).ready(function()
{
var img = $("img#back1");
var leftpos = img.position().left;
var toppos = img.position().top;
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = toppos+"px";
div.style.left = leftpos+"px";
div.innerHTML = '<font> back </font>';
div.style.background = '#CC0000';
document.body.appendChild(div);
});
After doing this, i am not getting text 'back' over the image. Here, the correct position can't be retrieved to be passed to the top and left of the div tag to specify text over it. Please suggest/ correct me if I've gone wrong somewhere.
Thanks
Upvotes: 2
Views: 8318
Reputation: 542
From http://api.jquery.com/position/
The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document.
As the dynamically created div
is attached to the body
, using offset()
instead of position
may help.
Upvotes: 1
Reputation: 3414
A better approach for adding text on image is to put image on background using css.It has a lot of benefits. You can check demo here
Upvotes: 1
Reputation: 26
The text does not appear or is simply out of place?
If you don't see the text maybe you need to specify the 'z-index' property in the DIV element.
For adding an attribute in javascript you can read: How to add/update an attribute to an HTML element using JavaScript?
Upvotes: 0
Reputation: 7536
You should visit this website:
It's a good tutorial for your porpuse. And I would suggest you learn a bit more of jQuery because all of your javascript code doesn't use ans jquery functionality expect the .ready()
Upvotes: 0