JavaScript & Copy Style

JavaScript & copy style

eval('oRow.cells[1].style.'+strAttribute)

Never use eval like this(*). In JavaScript you can access a property whose name is stored in a string using square brackets. object.plop is the same as object['plop']:

to.style[name]= from.style[name];

(*: never use eval at all if you can help it. There are only a few very specific and rare occasions you need it.)

Is there any way to loop over the style elements

The style object is supposed to support the DOM Level 2 CSS CSSStyleDeclaration interface. You could loop over the rules and apply them to another element like this:

for (var i= from.style.length; i-->0;) {
var name= from.style[i];
to.style.setProperty(name,
from.style.getPropertyValue(name),
priority= from.style.getPropertyPriority(name)
);
}

in IE?

No, IE does not support the whole CSSStyleDeclaration interface and the above won't work. However there is a simpler way not involving looping that will work on IE and the other browsers too:

to.style.cssText= from.style.cssText;

As simple as that! IE doesn't quite preserve the CSS text the way it should, but the difference doesn't matter for simple inline style copying.

However, as Pikrass said (+1), if you are copying a whole element and not just the styles, cloneNode is by far the most elegant way to do that.

How to copy all user provided styles from one object to another

Try something like this:

function ApplyStyles(select, span) {
var select = document.querySelector(select);
var span = document.querySelector(span);
var sheets = document.styleSheets;

for(var i = 0; i < sheets.length; i++) {
var rules = sheets[i].cssRules || sheets[i].rules;
for(var r = 0; r < rules.length; r++) {
var rule = rules[r];
var selectorText = rule.selectorText;
if(document.querySelector(selectorText) == select){
for(var l = 0; l < rule.style.length; l++){
span.style[rule.style[l]] = rule.style[rule.style[l]];
}
}
}
}
}

Then use the function like this:

ApplyStyles("#selection", "#span");

Here's a JSFiddle for example: https://jsfiddle.net/rsLnaw56/2/

How this works is it finds all external styles applied to the select element and applies it to the span element.

javascript copy element to clipboard with all styles

You can try the following fiddle. It works with every text style there is and it's interoperable with MS Word and Pages (I just tested it).

The code is pretty straightforward so I wouldn't really get into the depths of it, but feel free to drop me any questions should you feel like. :)

const copyWithStyle = ( element ) => {

const doc = document;
const text = doc.getElementById( element );
let range;
let selection;

if( doc.body.createTextRange ) {

range = doc.body.createTextRange();
range.moveToElement( text );
range.select();

} else if ( window.getSelection ) {

selection = window.getSelection();

range = doc.createRange();
range.selectNodeContents( text );

selection.removeAllRanges();
selection.addRange( range );

}

document.execCommand( 'copy' );
window.getSelection().removeAllRanges();
document.getElementById( 'clickMe' ).value = 'Copied to clipboard!';

}

https://jsfiddle.net/aypdg3kL/

From the example in JSFiddle

HTML

<div id="text" style="color:red">
<i>Hello</i> world!
</div>
<input id="btn" onclick="CopyToClipboard('text')" type="button" value="Copy" />

JS

function CopyToClipboard(element) {

var doc = document
, text = doc.getElementById(element)
, range, selection;

if (doc.body.createTextRange)
{
range = doc.body.createTextRange();
range.moveToElementText(text);
range.select();
}

else if (window.getSelection)
{
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById("btn").value="Copied";
}

Javascript: Open new window and copy over css references from the current window

Before opening the new document, you could create a STYLE tag in the existing document and populate that with all of the styles from either the LINK or STYLE tags in the header. You could then just copy that tag into the end of the new document.

Something like the following:

function showStyles() {
let ss = document.styleSheets;
let copycss = document.createElement("style");
// div just to show that styles are being found
let copydiv = document.getElementById("copiedstyles");
for (let i = 0; i < ss.length; i++) {
for (let j = 0; j < ss[i].cssRules.length; j++) {
let css = ss[i].cssRules[j].cssText;
copycss.innerHTML += css + "\n";
// Just for testing
copydiv.innerHTML += css + "<br>";
}
}
copycss.innerHTML += "button {color:purple;}\n";
copydiv.innerHTML += "button {color:purple;}<br>";
document.body.appendChild(copycss);
}
.blah {color:red;}
button {color:green;}
<button onclick="showStyles();">Show styles</button>
<div id="copiedstyles"></div>

Set / Copy javascript computed style from one element to another

Update:
As @icl7126 suggested, here is a shorter version for practically the same usage.
good thing to remember that this code would not run on most/older browser if not pre-compiled.

Original (ES 2017):

function copyNodeStyle(sourceNode, targetNode) {
const computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}

Precompiled (ES 5):

function copyNodeStyle(sourceNode, targetNode) {
var computedStyle = window.getComputedStyle(sourceNode);
Array.from(computedStyle).forEach(function (key) {
return targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key));
});
}
#

original answer posted on Nov '13. CSS variables were not supported back then. (first introduces on firefox on Jul 2014)

#

Thats it! I got it :)

Iv'e seen that lots of people view this question,
So below is more detailed and clean code.

var copyComputedStyle = function(from,to){
var computed_style_object = false;
//trying to figure out which style object we need to use depense on the browser support
//so we try until we have one
computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

//if the browser dose not support both methods we will return null
if(!computed_style_object) return null;

var stylePropertyValid = function(name,value){
//checking that the value is not a undefined
return typeof value !== 'undefined' &&
//checking that the value is not a object
typeof value !== 'object' &&
//checking that the value is not a function
typeof value !== 'function' &&
//checking that we dosent have empty string
value.length > 0 &&
//checking that the property is not int index ( happens on some browser
value != parseInt(value)

};

//we iterating the computed style object and compy the style props and the values
for(property in computed_style_object)
{
//checking if the property and value we get are valid sinse browser have different implementations
if(stylePropertyValid(property,computed_style_object[property]))
{
//applying the style property to the target element
to.style[property] = computed_style_object[property];

}
}

};


Related Topics



Leave a reply



Submit