Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 246
Justin Meltzer Avatar asked Dec 16 '22 16:12

Justin Meltzer


2 Answers

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;
}
like image 82
fx_ Avatar answered Dec 19 '22 05:12

fx_


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.

like image 29
Christian Mann Avatar answered Dec 19 '22 05:12

Christian Mann