Felipe Xavier
Felipe Xavier

Reputation: 165

Add element on top of image dynamically

When I click the button, it has to add an object (img, p) inside the div and the image with border and then take the position of that object, (x, y coordinates).

screenshot

How can I make this using JQuery?

HTML:

<div style="height: 440px; border: 1px solid; width: 880px; margin-top: 50px; margin-left: -12px;">
    <img id="imagem-principal" width="880" height="440" class="custom_media_image attachment-post-thumbnail" src="<?= $segunda_imagem; ?>">
</div>

Upvotes: 2

Views: 2274

Answers (1)

Jonathan Lam
Jonathan Lam

Reputation: 17351

To have a button create a new <img> and place it on top, add the following styles:

div {
    position: relative;
}
img:not(#imagem-principal) {
    position: absolute;
}

Then, you can add an onclick listener in jQuery:

$("#addImg").click(function() {

    // set x and y to what you want
    var xCoor = // X_COORDINATE;
    var yCoor = // Y_COORDINATE;

    var newImg = $("<img src='/* IMAGE_URL */' />");
    newImg.css({left: xCoor, top: yCoor});
    $("div").append(newImg);
});

This will create a new image with the given x and y coordinates on top of the other image.

See working example on JSFiddle.net.

Upvotes: 1

Related Questions