Git Product home page Git Product logo

jss's Introduction

JSS

A simple JavaScript library for retrieving and setting CSS stylesheet rules.

  • Tiny - only 4KB minified
  • No dependencies
  • MIT Licensed
  • Supports FF, Chrome, Safari, Opera, and IE9+

Why generate CSS with JavaScript?

  • To set styles that need to be calculated or retrieved
  • To set behavioural styles for your widget or plugin so that consumers aren't forced to include a stylesheet for core functionality
  • To dynamically apply styles without cluttering your HTML (as is the case with inline styles)
  • To set styles on all current and future elements

Usage

Download and include jss.js (or the minified file) in your HTML:

<script type="text/javascript" src="jss.js"></script>

If your project uses Bower for package management you can run the following command instead:

bower install jss

jss.set(selector, properties) to add a new rule or extend an existing rule:

jss.set('.demo', {
    'font-size': '15px',
    'color': 'red'
});

jss.get([selector]) to retrieve rules added via JSS:

jss.get('.demo');
// returns the following:
{
    'font-size': '15px',
    'color': 'red'
}
    
jss.get();
// returns the following:
{
    '.demo': {
        'font-size': '15px',
        'color': 'red'
    }
}

jss.getAll(selector) to retrieve all rules that are specified using the selector (not necessarily added via JSS):

jss.getAll('.demo');
// returns the following:
{
    'font-size': '15px',
    'color': 'red',
    'font-weight': 'bold'
}

jss.remove([selector]) to remove rules added via JSS:

jss.remove('.demo'); // removes all JSS styles matching the selector
jss.remove();        // removes all JSS styles

jss's People

Contributors

alexisducastel avatar chrisburgess7 avatar dvtng avatar editht avatar seththetech avatar shole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jss's Issues

Error - rules[i].selectorText is undefined

Just tried this JSS script out to try and make some jquery hover functions a little bit more streamlined with the CSS styles already set.

I seem to be getting the following error:

rules[i].selectorText is undefined

At first i thought it was because i was referencing an element that didn't exist, but that's now not the case.

var linksHoverColour = jss('#links li a:hover').get()['color'];

Am i using the code correctly?

CSS property parsing

I'm using JSS to produce transform rules, and it took me a while to work out that the reason it wasn't working with my translate3d(x,y,z)-format transforms was that it was validating input against the CSSOM and failing my passed values. I'm now using matrix(โ€ฆ)-format property values, and it's behaving.

This is an interesting design choice โ€” why parse the input rules? Why not just pass the whole rule in as a string and see what the browser makes of it?

jss._getRules sometimes causing null dereference when using Chrome

I am finding a null dereference exception is being triggered when using jss with Chrome 12.0. In jss._getRules, the error is on the line "if (typeof sheet.length == 'number') {" where sheet is null.

Having done some digging, it appears to be that when jss._addSheet is called (to add an extra sheet to store the new rules) document.styleSheets does not get updated directly after the head.appendChild(styleNode). This causes the jss._nodeToSheet function to fail to find the newly created sheet.

My solution (hack?) was to add some code after the appendChild to look in the DOM for the stylesheets and update the sheets variable accordingly:

jss._addSheet = function () {
    var styleNode = doc.createElement('style'),i;
    styleNode.type = 'text/css';
    styleNode.rel = 'alternate stylesheet';
    head.appendChild(styleNode);
    var s = doc.getElementsByTagName('style');
    sheets = [];
    for(i=0; i<s.length; ++i){
        sheets.push(s[i].sheet); 
    }
    return jss._nodeToSheet(styleNode);
};

I'm sure there are more elegant solutions, but this got me out of my problem.

A stylesheet with no rules

I encountered a bug in line 101.
If rules is null then the code breaks over rules.length. Here is my fix:

rules = sheet.cssRules || sheet.rules;
if (rules == null) {
                return []; 
 }
for (i = 0; i < rules.length; i++) {

jss._removeRule not working in Opera 11

Hello again David.

It seems that the jss._removeRule does not work in Opera 11 (Linux version). parentSheet.deleteRule(rule) throws an DOMException. It seems that Opera only allow to provide an index as parameter as parentSheet.deleteRule(0) works. Any suggestions how we can solve that in a nice way?

no milestones

v0.3 is current... what is planned for this library?

(sorry, this is not really an issue, but not sure how else to communicate this / feel free to close).

How to reset to Json Object format

Hi,
the new version has changing the format of passing the css value. Before it was use as Json format:

{ backgroundColor : value } ( format before)

{ background-color : value } (format now)

Can it custom to use as Json format like before?

Thanks,

gd

Error in Chrome when using linked css file

The following error is raised when linking css : Uncaught TypeError: Cannot read property 'length' of null

Test with the following code:

HTML

<html>
    <head>
        <title>rule test</title>
        <link rel="stylesheet" type="text/css" href="rule.css">
        <script type="text/javascript" src="jss.js"></script>
        <script>
            function test(rule) {
                var str = jss(rule).get();
                jss(rule, { color: 'blue' });
            }
        </script>
        <style>
            .rule-test-local { color: green; }
        </style>
    </head>
    <body>
        <div class="rule-test-link" onclick="test('.rule-test-link');">test linked css</div>
        <div class="rule-test-local" onclick="test('.rule-test-local');">test local css</div>
    </body>
</html>

CSS

.rule-test-link { color: red; }

jss.get() and media queries

When using getAll(".classname") to get a css property, and the class has more than one occurance (in different media queries), jss always gets the class without media query, and not the active one.

I could've used it in my current project, as getComputedStyle() is also insufficient as the inline css also has the property i need to get.

basically, I need the transform property of the class in the current media query.

CSS:

.class {
   transform: scale(3); // i need this one when displayed on small screens
}
@media screen and (min-width: 1024px){
   .class {
      transform: scale(6); // i need this one when displayed on screens > 1024px
}

JS and screen > 1024px

document.querySelector(".class").style.transform = "scale(1)";

// ... other calculations

jss.getAll(".class").transform; // returns "scale(3)"
getComputedStyle(document.querySelector(".class")).transform; // returns "scale(1)"
// ????? // returns "scale(6)"

Cheers

storing selector in a variable doesn't seem to work

I am not sure I am doing something wrong, but I try to store the selector name in a variable like this:
$target = $this.closest('.whatever').find('.' + $identifier);
and try to change it like this:
jss.set($target, { borderColor: "#whatever" });
but I get this error:

Uncaught TypeError: t.toLowerCase is not a function

class selector does not seem to work

If I call:

jss.set('.myClass', {
'display': 'none'
});

the css is updated properly , and the display elements are updated as expected.

However, calling

jss.remove('.myClass');

has no effect.

Calling

jss.remove();

works though.

The .myClass style is not defined anywhere. If I do define it in a .css file included on the page, the behaviour is the same. If I use an element type selector instead of a class selector, remove seems to work as would be expected.

pseudo selector such as ::before and ::after support

I edited your code long ago for pseudo class support for all browsers.
but I can't pull request because used old code.
see my commit for details.

webkit supports pseudo selector with 2 colons (block pseudo selector in CSS3) (::before and ::after).
:before and :after are not work.
other browsers may works in old style pseudo selector (:before and :after).

How it works - go to my wiki

thanks.

jss namespace on bower

Hi,

I have got this issue cssinjs/jss#23

How do you feel about my implementation of jss?

Would you transfer your bower namespace in favor of my implementation?

I think the idea is basically the same.

Best,
Oleg

!important?

Is there a way to apply an !important modifier on a rule? It seems as if this fails to set when I try:

jss.set(".foobar",{"background-color":"#f00 !important"});

Without the !important, it works fine.

selectorText is case-sensitive

First thanks for that lib! I had a problem jss not working at all, this was the problem:
// Browsers report selectors in lowercase
if (selector) selector = selector.toLowerCase();

"Browsers report selectors in lowercase", Are you sure that is true? I tested Opera, Firefox and Chromium it doesn't looks like it.

Create the sheet on construction of jss instance

Instead of lazily creating the defaultSheet on set of a rule, create it on construction of jss. I ran across very confusing behavior when I was trying to interact with two different stylesheets using jss. Example:

var jss1 = jss.forDocument(document)
var jss2 = jss.forDocument(document)

jss2.set('#A', {
    color: 'green'
})
jss1.set('#A', {
    color: 'red'
})

I expected element #A to be green after both rules were set, but in fact, the element changes to red. The reason is that the stylesheet is created on the first set instead of on forDocument. It would be much cleaner to create the sheet on construction.

Is there a way to create a style in one stylesheet that's overridden by styles in another stylesheet?

I want to do something like this:

    var jssSheet1 = jss.sheet() // returns a jss instance with a new sheet created on the document
    var jssSheet2 = jss.sheet()

    jssSheet2.set('#A', {
        color: 'red'
    })
    jssSheet1 .set('#A', {
        color: 'green'
    })

But I want the results to be that #A remains red. Is there any way I can create a style later in time that is overridden by a style that was created earlier in time?

Some fixes

Hi, I know this script is pretty old but I needed something like this in a project of mine and I made some fixes to it to work with the newer browser versions.


if (!selector || ruleText === selector || ruleText === jss._swapAdjSelAttr(selector)) {

if (!selector || ruleText === selector || ruleText === jss._swapAdjSelAttr(selector) || ruleText === selector.replace(':','::')) {


result[propName] = rules[i].style[propName];

result[propName] = rules[i].style[propName] || rules[i].style[jss._toCamelCase(propName)];

Just 2 very quick fixed, the first one is for selecting pseudo classes in Chrome, the second one is for the get function to receive the correct data in FF.

This is far from completely working now, for example margin values are incorrect in FF, probably padding as well but I don't need those for now ;-)

In case anyone uses this still...

Sheet does not print out!

Why the sheet does not print out all rules and property when it append to head. It just show blank

<style type="text/css"></style>

How can I get the result of all styles and rules of the sheet? not just a property of one selector by use jss.get('selector'); or jss.getAll('selector');

I want like the whole sheet

Thanks,

gd

Publish on npm

I use npm, and I'm sure a bajillion more people do too. Would love to be able to pull this in via npm!

jss cannot read external css rules

i came to a situation when i need to check css rule of some jquery ui class loaded via external hoster stylesheet... in this case sheet.cssRules and sheet.rules arrays are empty.

Chrome.
image

Integrate with Angular

Does jss library integrate well with Angular?
Is there any documentation?

Thanks
dave

check if there is a css rule

Would be nice to have a function which, given a string, returns a boolean if there is a css rule or not for said string.

Css background values with vendor prefixes

Hello,

I wanted to use JSS to generate CSS rule like this:

body.mystyle {
    background-image: -moz-linear-gradient(top, rgba(0,0,0,0) 75%, rgba(0,0,0,0.65));
    background-image: -webkit-linear-gradient(top, rgba(0,0,0,0) 75%, rgba(0,0,0,0.65));
    background-image: -o-linear-gradient(top, rgba(0,0,0,0) 75%, rgba(0,0,0,0.65));
    background-image: -ms-linear-gradient(top, rgba(0,0,0,0) 75%, rgba(0,0,0,0.65));
    background-image: linear-gradient(top, rgba(0,0,0,0) 75%, rgba(0,0,0,0.65));
}

The API of JSS is great. But usage of Objects for css properties will not work in case like above.
Maybe there could be a new set method which will accept strings directly?

I would like to avoid browser detection and setting just the correct rule.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.