tea_clipper
tea_clipper

Reputation: 13

Copying specific styles from one element to another

I have this code that would copy the contents of one element and place it on another. But I would actually like to copy the inline style, especially the positioning. Is there a way to copy the position style only, so that the info window will appear exactly where the a.star is when I hover?

$(document).ready(function(){
  $('a.star').hover(function(){
    var instrument = '.instrument_info#' + $(this).attr('instrument');
    var htmlCode = $(instrument).html();
    $('.instrument_output .instrument_detail').html(htmlCode);
    $('.instrument_output').slideToggle();
  })
});

I want to get the inline positioning of this: <div class="instrument_info" id="drums" style="top:95px; left:294px"> and put it in another div. How can I insert this in my jQuery code?

Upvotes: 0

Views: 892

Answers (2)

Chris
Chris

Reputation: 26878

.html() doesn't include inline styles at all. You need to use the jQuery .css() function;

$(".target_elements").css({top: $("someElement").offset().top, left: $("someElement").offset().left});

And since .offset() returns a {top: ..., left: ...} object, you can write the above more compactly as:

$(".target_elements").css($("someElement").offset());

Upvotes: 2

Filip Dupanović
Filip Dupanović

Reputation: 33640

You'll have to read those properties from one DOM element and assign them to another.

 var foo_offset = $('#foo').offset() # returns {left: 100, top: 100}
 $('#bar').offset(foo_offset)        # #bar's offset set to #foo's

Check out the CSS documentation. All of the methods are designed with a signature that provides you the actual value of the property when called and assign objects to those properties if called with an additional argument.

Upvotes: 1

Related Questions