views:

3389

answers:

5

I'm looking for a way using jQuery to return an object of computed styles for the 1st matched element. I could then pass this object to another call of jQuery's css method.

For example, with width, I can do the following to make the 2 divs have the same width:

$('#div2').width($('#div1').width());

It would be nice if I could make a text input look like an existing span:

$('#input1').css($('#span1').css());

where .css() with no argument returns an object that can be passed to .css(obj).

(I can't find a jQuery plugin for this, but it seems like it should exist. If it doesn't exist, I'll turn mine below into a plugin and post it with all the properties that I use.)

Basically, I want to pseudo clone certain elements but use a different tag. For example, I have an li element that I want to hide and put an input element over it that looks the same. When the user types, it looks like they are editing the element inline.

I'm also open to other approaches for this pseudo cloning problem for editing. Any suggestions?

Here's what I currently have. The only problem is just getting all the possible styles. This could be a ridiculously long list.


jQuery.fn.css2 = jQuery.fn.css;
jQuery.fn.css = function() {
    if (arguments.length) return jQuery.fn.css2.apply(this, arguments);
    var attr = ['font-family','font-size','font-weight','font-style','color',
 'text-transform','text-decoration','letter-spacing','word-spacing',
 'line-height','text-align','vertical-align','direction','background-color',
 'background-image','background-repeat','background-position',
 'background-attachment','opacity','width','height','top','right','bottom',
 'left','margin-top','margin-right','margin-bottom','margin-left',
 'padding-top','padding-right','padding-bottom','padding-left',
 'border-top-width','border-right-width','border-bottom-width',
 'border-left-width','border-top-color','border-right-color',
 'border-bottom-color','border-left-color','border-top-style',
 'border-right-style','border-bottom-style','border-left-style','position',
 'display','visibility','z-index','overflow-x','overflow-y','white-space',
 'clip','float','clear','cursor','list-style-image','list-style-position',
 'list-style-type','marker-offset'];
    var len = attr.length, obj = {};
    for (var i = 0; i < len; i++) 
        obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]);
    return obj;
}

Edit: I've now been using the code above for awhile. It works well and behaves exactly like the original css method with one exception: if 0 args are passed, it returns the computed style object.

As you can see, it immediately calls the original css method if that's the case that applies. Otherwise, it gets the computed styles of all the listed properties (gathered from Firebug's computed style list). Although it's getting a long list of values, it's quite fast. Hope it's useful to others.

+3  A: 

It's not jQuery but, in Firefox, Opera and Safari you can use window.getComputedStyle(element) to get the computed styles for an element and in IE you can use element.currentStyle. The returned objects are different in each case, and I'm not sure how well either work with elements and styles created using Javascript, but perhaps they'll be useful.

In Safari you can do the following which is kind of neat:

document.getElementById('b').style.cssText = window.getComputedStyle(document.getElementById('a')).cssText;
Richard M
thanks. after looking into this problem more, these methods are used by jquery in the css method, so it would be rewriting what's already there.
Keith Bentrup
+2  A: 

Now that I've had some time to look into the problem and understand better how jQuery's internal css method works, what I've posted seems to work well enough for the use case that I mentioned.

It's been proposed that you can solve this problem with CSS, but I think this is a more generalized solution that will work in any case without having to add an remove classes or update your css.

I hope others find it useful. If you find a bug, please let me know.

Keith Bentrup
+1  A: 

I dont know if you're happy with the answers you got so far but I wasn't and mine may not please you either, but it may help someone else.

After pondering upon how to "clone" or "copy" elements' styles from one to another I have come to realize that it was not very optimal of an approach to loop through n and apply to n2, yet we're sorta stuck with this.

When you find yourself facing these issues, you rarely ever need to copy ALL the styles from one element to another... you usually have a specific reason to want "some" styles to apply.

Here's what I reverted to:

$.fn.copyCSS = function( style, toNode ){
  var self = $(this);
  if( !$.isArray( style ) ) style=style.split(' ');
  $.each( style, function( i, name ){ toNode.css( name, self.css(name) ) } );
  return self;
}

You can pass it a space-separated list of css attributes as the first argument and the node you want to clone them to as the second argument, like so:

$('div#copyFrom').copyCSS('width height color',$('div#copyTo'));

Whatever else seems to "misalign" after that, I'll try to fix with stylesheets as to not clutter my Js with too many misfired ideas.

Quickredfox
+1  A: 

I like your answer Quickredfox. I needed to copy some CSS but not immediately so I modified it to make the "toNode" optional.

$.fn.copyCSS = function( style, toNode ){
  var self = $(this),
   styleObj = {},
   has_toNode = typeof toNode != 'undefined' ? true: false;
 if( !$.isArray( style ) ) {
  style=style.split(' ');
 }
  $.each( style, function( i, name ){ 
  if(has_toNode) {
   toNode.css( name, self.css(name) );
  } else {
   styleObj[name] = self.css(name);
  }  
 });
  return ( has_toNode ? self : styleObj );
}

If you call it like this:

$('div#copyFrom').copyCSS('width height color');

Then it will return an object with your CSS declarations for you to use later:

{
 'width': '140px',
 'height': '860px',
 'color': 'rgb(238, 238, 238)'
}

Thanks for the starting point.

HexInteractive