2

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

1
  • Can you please post your HTML code also here with CSS,Better if you could provide JSFiddle link for that.Might be you're missing Z-index for your div not sure.
    – Gurvinder
    Feb 14, 2012 at 11:34

4 Answers 4

1

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

demo

0
1

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.

0

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()

0

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.