2

Hi mighty Wizards of the web,

Question:

Is it possible to copy the contents of a specifiy stylesheet to the users clipboard?

Example:

  1. The User clicks on a "copy to clipboard" button.
  2. The contents of the forms.css is copied to his clipboard.
  3. The User can paste those content in hier own project.

Possible Approaches:

  1. Use a plugin: The copycss plugin seems to be coming close to what I need, but copies only the css of specified DOM elements. I would need the css-code of a whole stylesheet. Example: Everything that is related to form elements (copied from the forms.css)

  2. Copy from the DOM: Another approach would be to insert the stylesheets content into a hidden textfield and copy it from there via jQuery. But I'm not sure if its possible to somehow grab the content and insert it into the DOM.

Any Ideas?

I'm grateful for any push in the right direction.

All the best! Cheers!

Arrowcatch
  • 1,374
  • 2
  • 15
  • 20

2 Answers2

1

To get a stylesheet as a string you can use document.styleSheets, and do something like this

var styleSheet  = document.styleSheets[0],
    styleString = $.map(styleSheet.rules, function(rule) {
        return 'cssText' in rule ? rule.cssText : '';
}).join("\n");

note that document.styleSheets is a collection, so [0] gets the first stylesheet in the page, [1] gets the second etc.

As for saving to the clipboard, that can be rather complicated, the prefered way is to use a prompt, something like this

window.prompt("Copy to clipboard: Ctrl+C, Enter", styleString);

telling the user to manually copy the string.

If you want a cross browser way to use a button instead, you would have to use flash, and there are plugins for this, ZeroClipboard is most commonly used, but there's also Clippy, which is a little easier to use.

adeneo
  • 293,187
  • 26
  • 361
  • 361
0

See 400212 for an overview of methods for copying data to clipboard.

As for getting the CSS;

var styles = document.styleSheets[0].href;
$.get(styles, function(data) {
  console.log(data); // call the clipboard copy function on data here
});
Community
  • 1
  • 1
thykka
  • 481
  • 2
  • 9