views:

54

answers:

2

I have an element of an arbitrary type. I'd like to create another element, of either the same or a different type that has the same position and size as the first. The element may or may not be positioned.

For example, I might start with a <select> with a certain size, possibly dependent on its contents, i.e. width/height auto. I want to create a new <div> that appears at the same position and has the same size.

I've tried copying the element's float, clear, position, width, height, margins and padding, but this is a little cumbersome. Also, while it works in Firefox, I'm running into some strange issues when testing on Webkit. Before I spend much more time figuring it out, I'd like to know whether there's some jQuery or jQuery UI functionality that already takes care of what I want to do.

I realize that this question is similar to an existing one, but mine has the important distinction of needing to work with elements of differing types, which precludes clone as a solution.

A: 

How about just copying the element's offset and absolutely positioning it on the page?

Say you had an input element somewhere on the page with dimensions 100x25px.

<input type="text" id="firstname" style="width: 100px; height: 20px" />

And you wanted to place a div right on top of it (and hide the input).

// Store the input in a variable
var $firstname = $("#firstname");

// Create a new div and assign the width/height/top/left properties of the input
var $newdiv = $("<div />").css({
    'width': $firstname.width(),
    'height': $firstname.height(),
    'position': 'absolute',
    'top': $firstname.offset().top,
    'left': $firstname.offset().left
});

// Add the div to the body
$(body).append($newdiv);
Marko
This approach has issues with fluid layouts. If an element is inserted before "#firstName" which moves firstName down the page "newdiv" would not line up properly.
David Murdoch
This is probably true, a different solution is needed in liquid layout situations.
Marko
A: 

This is NOT efficient, tested, or complete. And it is probably similar to what you are already doing. But I thought I'd post it anyways:

var positioningProps = ["float","position","width","height","left","top","marginLeft","marginTop","paddingLeft","paddingTop"];
var select = $("#mySelect");
var div = $("<div>").hide().before(select);
// don't do this kind of loop in production code
// http://www.vervestudios.co/jsbench/
for(var i in positioningProps){
    div.css(positioningProps[i], select.css(positioningProps[i])||"");
}
select.hide();
David Murdoch