How do you dynamically position one element on top of another?

13,559

Solution 1

This is more like a CSS question. You want to make sure the parent element (#video_div) is positioned relatively (position: relative) and the inserted element (the img) is positioned absolutely (position: absolute)

Hook it to the top left, make sure they're the same size and you're golden.

#video_div {
  position: relative;
  width: 300px;
  height: 300px;
}

#video_div img {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 300px;
  height: 300px;
}

Solution 2

Assuming you mean directly on top of it (obscuring it) in the z-order, a combination of JQuery's .position() method and absolute positioning should do the trick.

$('<div>New Element</div>').css({
    "position" : "absolute",
    "left"     : $foo.position().left,
    "top"      : $foo.position().top
}).appendTo($container);

Note: $container must contain both the dynamically generated element and the target element.

Share:
13,559
Justin Meltzer
Author by

Justin Meltzer

Updated on June 04, 2022

Comments

  • Justin Meltzer
    Justin Meltzer almost 2 years

    I'm dynamically appending some html with jQuery and I want to insert it directly on top of another element. How do I do this?

    this is the code in my application.js file:

    $(document).ready(function() {
    $('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
          $("#video_div").append($("<img>", { src: oembed.thumbnail_url, width:200 }));
       });
    });
    

    The image is being inserted dynamically, and I want it to be directly on top of this:

    <div id="video_div"><%= link_to 'video', @video.video_url, :class => 'oembed' %></div>