Building A Relationship Between CSS & JavaScript

Advertisement

jQuery, Prototype, Node.js, Backbone.js, Mustache and thousands of JavaScript microlibraries all combine into a single undeniable fact: JavaScript is popular. It’s so popular, in fact, that we often find ourselves using it in places where another solution might be better in the long run.

Even though we keep JavaScript, CSS and HTML in different files, the concepts behind progressive enhancement are getting all knotted up with every jQuery plugin we use and with every weird technique that crops up. Because JavaScript is so powerful, there are a lot of overlaps in capability between JavaScript and HTML (building document structure) and JavaScript and CSS (injecting style information). I’m not here to pick on any JavaScript library, bootstrap or boilerplate; I’m just here to offer a little perspective as to where we are and how we can realign our goals.

Relationship Image
Image Credit: opensourceway.

(Smashing’s side note: Have you already pre-ordered the brand new Smashing Mobile Book? The book features everything you need to know as a designer or developer to create beautiful and rich mobile experiences. Get your book today!)

Keeping CSS Out Of Your JavaScript

CSS can hook into HTML with a variety of different selectors; this isn’t anything new. By using IDs, classes or any attribute you can think of (even custom attributes), you have easy access to style an element. You can also do this with a slew of JavaScript methods, and honestly, it’s the same basic process with a different syntax (one of my JavaScript ah-ha moments). Being able to natively access HTML from JavaScript and from CSS is one of the reasons progressive enhancement has been such a successful development model. It allows a point of reference to guide us and to serve as a reminder as we develop a project, so we don’t “cross the streams”.

But, as you move forward with JavaScript and build applications with highly interactive elements, it gets harder to not only keep HTML out of your JavaScript, but also to catch yourself before injecting style information into a document. Of course, the case for not injecting style with JavaScript certainly isn’t a binary one (yes/no, true/false, 0/1); there are plenty of cases where you might need to apply styles progressively, for example, in a drag and drop interface where positioning information needs to be constantly updated based on cursor (or finger) position.

But generally speaking, you can safely house all the style information you need within CSS and reference styles as reusable classes. This is a much more flexible model than sprinkling CSS throughout a JavaScript file, and it very closely compares to the model of adding style information into your HTML. We follow this model when it’s only HTML and CSS, but for some reason it has a tendency to fall apart once JavaScript gets added into the mix. It’s certainly something we need to keep an eye on.

A lot of front-end developers take real pride in having clean HTML. It’s easy to work with, and to certain super-geeks it can even be artful. It’s great to have clean, static HTML, but what good is that if your generated HTML is riddled with injected style and non-semantic markup? By “generated HTML,” I’m referencing how the HTML looks after it’s been consumed and barfed back up after being passed around all those plugins and extra JavaScript. If step one to having clean HTML and separated progressive enhancement layers is to not use a style attribute, I’d have to say that step two is to avoid writing JavaScript that injects a style attribute for you.

Cleaning Up Your HTML

We can probably all agree that blindly using a technology is a terrible idea, and I think we’re at a point with jQuery where we are, indeed, blindly using a lot of the features without fully understanding what’s going on under the hood. The example I lean on pretty heavily for keeping CSS out of my JavaScript is the behavior of jQuery’s hide() method. Based on the principles of progressive enhancement, you wouldn’t code something with inline CSS like this:

<div class="content-area" style="display:none;"></div>

We don’t do that because a screen reader won’t pick up an element if the style is set to display:none, and it also muddies up the HTML with unnecessary presentational information. When you use a jQuery method like hide(), that’s exactly what it does: it will set a style attribute on the target area and add a display property of none. It’s very easy to implement, but not very good for accessibility. It also violates the principles of progressive enhancement when you inject style into the document like that (we’re all sorts of messed up, huh?). It’s not uncommon for this method to be used within a tabbing interface to hide content. The result is that the content is nonexistent to a screen reader. Once we realize that adding style from JavaScript isn’t ideal in most cases, we can move it into the CSS and reference it as a class:

CSS

.hide {
   display: none;
}

jQuery

$('.content-area').addClass('hide');

We still have to address the accessibility problem of hiding content with display:none, but since we’re not using a built-in jQuery method anymore, we can control exactly how content gets hidden (whichever accessible method you prefer is probably fine). For example we could do something like:

CSS

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

.remove {
   display: none;
}

In the above example, you can see that even though both classes result in content being removed from view, they function very differently from an accessibility standpoint. Looking at the code like this makes it clear that we really are dealing with style information that belongs in a CSS file. Using utility classes in this way can not only help your JavaScript slim down, but also have double usage in an Object Oriented CSS (OOCSS) development model. This is truly a way to not repeat yourself (Don’t Repeat Yourself, or DRY) within CSS, but also across a whole project, creating a more holistic approach to front-end development. Personally, I see a lot of benefit in controlling your behaviors this way, but some people have also called me a control-freak in the past.

Web and Team Environments

This is a way we can start opening up lines of communication between CSS and JavaScript and lean on the strengths of each language without overdoing it. Creating a developmental balance on the front end is very important, because the environment is so fragile and we can’t control it like we can on the back end with a server. If a user’s browser is old and slow, most of the time you can’t sit down and upgrade it (aside: I do have my grandmother using Chrome); all you can do is embrace the environmental chaos, build for the best and plan for the worst.

Some people have argued with me in the past that this style of development, where you’re referencing CSS classes in JavaScript, doesn’t work well in team development environments because the CSS is usually built by the time you’re diving into the JavaScript, which can cause these classes to get lost in the mix and create a lot of inconsistency in the code (the opposite of DRY). To those people I say: poke your head over the cube wall, open AIM, GTalk or Skype, and communicate to the rest of the team that these classes exist specifically to be used with JavaScript. I know the concept of developers communicating outside of GIT commit messages seems like madness, but it’ll be okay, I promise.

Using Behavioral CSS With JavaScript Fallbacks

Using these CSS objects as hooks for JavaScript can go far beyond simple hiding and showing of content into an area of behavioral CSS, transitions, animations and transforms that are often done with JavaScript animations. With that in mind, lets take a look at a common interaction model of fading out a div on click, and see how it would be set up with this development model, while providing the proper fallbacks for browsers that might not support the CSS transition we’re going to use.

For this example we’ll be using:

First, let’s set up our body element:

<body>
    <button type="button">Run Transition</button>
    <div id="cube"></div><!--/#cube-->
</body>

From there we’ll need to set up the CSS:

#cube {
   height: 200px;
   width: 200px;
   background: orange;
   -webkit-transition: opacity linear .5s;
      -moz-transition: opacity linear .5s;
        -o-transition: opacity linear .5s;
           transition: opacity linear .5s;
}

.fade-out {
   opacity: 0;
}

Before we add on the JavaScript layer, lets take a moment and talk about the flow of what’s going to happen:

  1. Use Modernizr to check for CSS Transition support
  2. If Yes
    1. Set up a click event on the button to add a “fade-out” class to #cube
    2. Add another event listener to catch when the transition is finished so we can time the execution of a function that will remove #cube from the DOM.
  3. If No
    1. Set up a click even on the button to use jQuery’s animate() method to manually fade #cube out.
    2. Execute a callback function to remove #cube from the DOM.

This process will introduce a new event called transitionend, which will execute at the end of a CSS transition. It’s amazing, FYI. There is also a companion event called animationend, which will execute at the end of a CSS animation for more complex interactions.

First thing we need to do is set up our variables in the JavaScript:

(function () {

   // set up your variables
   var elem = document.getElementById('cube'),
       button = document.getElementById('do-it'),
       transitionTimingFunction = 'linear',
       transitionDuration = 500,
       transitionend;

   // set up the syntax of the transitionend event with proper vendor prefixes
   if ($.browser.webkit) {
       transitionend = 'webkitTransitionEnd'; // safari & chrome
   } else if ($.browser.mozilla) {
       transitionend = 'transitionend'; // firefox
   } else if ($.browser.opera) {
       transitionend = 'oTransitionEnd'; // opera
   } else {
       transitionend = 'transitionend'; // best guess at the default?
   }

   //... rest of the code goes here.

})(); // end wrapping function

You might notice that our new transitionend event needs a vendor prefix; we’re doing a little browser detection to take care of that. Normally you might detect for the vendor prefix and add it onto the event name, but in this instance the cases for the syntaxes are a little different, so we need to get the whole name of the event for each prefix.

In the next step we’ll use Modernizr to detect support, and add our event listeners to each case (all of this stuff gets added inside the wrapping function):

// detect for css transition support with Modernizr
if(Modernizr.csstransitions) {

    // add our class on click
    $(button).on('click', function () {
       $(elem).addClass('fade-out');
    });

    // simulate a callback function with an event listener
    elem.addEventListener(transitionend, function () {
       theCallbackFunction(elem);
    }, false);

} else {

   // set up a normal click/animate listener for unsupported browsers
   $(button).on('click', function () {

       $(elem).animate({
           'opacity' : '0'
       }, transitionDuration, transitionTimingFunction, function () {
           theCallbackFunction(elem);
       });

   }); // end click event

} // end support check

Finally, we need to define a shared function between the two actions (DRY) which executes after the transition (or animation) is complete. For the sake of this demonstration we can just call it theCallbackFunction() (even though it’s not technically a callback function). It will remove an element from the DOM and spit out a message in the console letting us know that it worked.

// define your callback function, what happens after the transition/animation
function theCallbackFunction (elem) {

   'use strict';

   // remove the element from the DOM
   $(elem).remove();

   // log out that the transition is done
   console.log('the transition is complete');

}

In the browser, this should work the same way in IE 7 (on the low end) as it does in mobile Safari or Chrome for Mobile (on the high end). The only difference is under the hood; the experience never changes for the user. This is a way you can use cutting-edge techniques without sacrificing the degraded user experience. It also keeps CSS out of your JavaScript, which was really our goal the whole time.

The Moral Of The Story

You might be asking yourself why we should even bother going through all this work. We wrote about 60 lines of JavaScript to accomplish the same design aesthetic that could be created with eight lines of jQuery. Well, no one ever said that keeping clean code and sticking to progressive enhancement was the easiest thing to do. In fact, it’s a lot easier to ignore it entirely. But as responsible developers, it’s our duty to build applications in a way that is accessible and easily scales to the future. If you want to go that extra mile and create a seamless user experience as I do, then it’s well worth the extra time it takes to dot all the i’s and cross all the t’s in a project to create an overall experience that will gracefully degrade and progressively enhance.

Using this model also lets us lean heavily on CSS for its strengths, like responsive design and using breakpoints to redefine your interaction at the various screen sizes. It also helps if you’re specifically targeting a device with a constrained bandwidth, because, as we all know, CSS is much lighter than JavaScript in both download and execution time. Being able to offload some of the weight JavaScript carries onto CSS is a great benefit.

In production, we are currently using CSS animations and transitions for micro interactions like hover effects and maybe a spinning graphic or a pulsating knot. We’ve come to a point where CSS is a pretty powerful language that performs very well in the browser and it’s okay to use it more heavily for those macro interactions that are typically built using JavaScript. If you’re looking for a lightweight and consistent experience that’s relatively easy to maintain while allowing you to use the latest and greatest browser features — it’s probably time to start mending fences and build strength back into the relationship between CSS and JavaScript. As a great man once said, “The key to writing great JavaScript is knowing when to use CSS instead.” (It was me… I said that.)

(cp)

↑ Back to top

Tim Wright is the Senior User Experience Designer and Developer at Fresh Tilled Soil, a UX design agency out of Boston, MA.

Tim is a frequent speaker, blogger, article writer, and published author. In fact, he recently wrote a book on JavaScript: Learning JavaScript: A Hands-On Guide to the Fundamentals of Modern JavaScript. You can find more of his writings at CSSKarma

  1. 1

    I like the premise of the article – especially good for newcomers to learn to keep style info out of their JS.

    But $.browser….seriously?

    0
    • 2

      Great article. I completely support your point of view on keeping styles out of script.

      I do, however, agree with @Adam about the use of $.browser too though. Plus on some day in the, possibly distant, future when a browser drops support for it’s prefixed event name, the transition end event will no longer fire if this code is used.

      0
    • 3

      Do you have an alternative method of generating a vendor prefix without browser detection?

      0
      • 4

        Yes, you can use if (typeof document.body.style.webkitTransitionEnd !== “undefined”) etc.

        0
      • 5

        Something like :

        var tEvents = {
        ‘WebkitTransition’ : ‘webkitTransitionEnd’,
        ‘MozTransition’ : ‘transitionend’,
        ‘OTransition’ : ‘oTransitionEnd otransitionend’,
        ‘msTransition’ : ‘MSTransitionEnd’,
        ‘transition’ : ‘transitionend’
        },
        tEvent = tEvents[Modernizr.prefixed('transition')];

        0
        • 6

          Copy and pasted for modernizr docs?

          0
          • 7

            Copied and pasted from a project of mine. Likely to come from modernizr docs or from the same source than modernizr’s doc, i’ve used this for a long time, can’t remember.

            Modernizr’s not exactly the same : note the ‘oTransitionEnd otransitionend’ for Opera. I remember it solved a bug in Opera… 11 I think. Not sure if relevent now Opera is at version 12.

            0
          • 8

            I don’t think there’s anything wrong in copy-pasting it from Modernizr, although he said he didn’t, it wouldn’t have been a “crime” to do so. The point was to provide an alternative for $.browser, which he did.

            0
    • 9

      Hi Adam, I agree that browser detection is generally frowned upon. It should still work since the JS fallback to a non-prefixed version at the end though. Could you share your method of generating vendor extensions without browser detection?

      0
  2. 12

    One problem with using CSS classes to hide stuff instead of jQuery’s functions is that you can’t use effects and timings to do that (or have to resort to doing the timers yourself). I suppose you could do them with CSS transitions etc but IMO it’s more trouble than it’s worth.

    0
    • 13

      With CSS animations you can do timing, delay and effects, so I’m a strong believer in serving the animations through CSS to the browsers that support CSS3 animations and for those who don’t you serve a JavaScript fallback. It is double work in most cases, but this feels to me the right way of doing this these days.

      0
      • 14

        There are plugins for JQuery and MooTools that automate the CSS3 fallback option for the animations. However you must realize that they will stick all the style attributes inline (which is the oposite of what this article is suggesting).

        0
      • 15

        I do too support CSS animations but unfortunately there are some disturbing limitations, e.g. you can’t animate form 0 to auto.

        0
    • 16

      Hi Kasakka, you could do something like: $(elem).removeClass(‘hide’).hide().fadeIn(); if you wanted to take advantage of timing functions. The point is really not using hide() (in this case) to remove content from view, but rather to use a css where you have some more control.

      0
    • 17

      Effects and transitions are (usually) style, and should probably be in your CSS anyways. We just didn’t have the ability to do it that way until recently. I think that implementing them with CSS is better from a standpoint of theoretical purity, and then you could fall back to just not having the effect if it’s not crucial.

      0
  3. 18

    ‘do-it’ is never used again, is the the ID of the button?

    0
  4. 20

    I agree too, although you’d be hard pressed to iron out all of the examples in the jQuery library/plugins where .hide() is used to hide content.

    I’m just curious why you use document.getElementById and store a reference to the element in a variable when you may just as well use $(“#cube”) and store a reference to the jQuery object that can then be used directly, saving you a bit of time.

    I’m also wondering what the speed implications are on adding/removing a class compared to setting an inline style. It’s a more elegant solution, but in major web apps, would it be detrimental to the overall speed of the app? Just curious.

    0
    • 21

      CSS transitions are hardware accelerated and will for that reason perform better – especially on mobile devices; setting an inline style attribute 100 times to simulate an animation is obviously more stressful than simply add a class and let the hardware do the rest.

      0
      • 22

        @Ivar – With respect, in my experience, this is not always the case. If you want a really slow animation, it’ll be noticeably smoother if you animate it using JavaScript than with CSS. Whilst the browsers do choose to hardware accelerate some animations, they don’t do all of them by default and their heuristics for choosing when to switch it on or off don’t always match designer/developer/client expectations. You can prompt the renderer by trying to do 3D animations and then only animating in one or two planes, but this doesn’t always have the effect you’d hope and also isn’t writing “intentional” code. (i.e. you’re telling the browser to introduce a side-effect, then nullifying some aspects of the side-effect, rather than explicitly and precisely describing what you want to happen. The latter is always a better aim).

        0
  5. 23

    Here’s a common problem we have with using CSS and JS together in this fashion.

    - Designer comes up with some branding classes.
    - Developer develops JS behaviors around said classes.
    - Designer or Developer come back at a later date and change the class name in the CSS and the templates.
    - JS stops working or content doesn’t display as expected because JS is still using the old class name.

    Of course “testing, testing, testing” comes to mind, but testing is the first thing to go when timelines are tight or budgets are squeezed. Plus sometimes this functionality is deep down in some page that you’re not even expecting would be impacted.

    So how do we ensure that designers/developers know that when they change a class name or ID in one place that they have to go back through and check multiple other sources for that class name and make changes there as well? How do you minimize the need for such excessive change work?

    0
    • 24

      Since when comes a designer with branding classes? This is part of the job of the developer. I do both, but still if I create a mock-up in PS (which I hardly do these days btw) I don’t think of class names. I would organize the layer palette with header, content, sidebar, footer, etc. but this doesn’t mean that I would use them as class names when I start developing. Okay it’s silly example cause normally i would name them with given names, but i’m certainly not busy with other class names when I’m designing in PS.

      0
      • 25

        I work in a very dynamic place. We have a core set of designers that work only on one limited product area. In other product areas it’s up to the developer. Then sometimes for new products we bring in outside firms. Some of those firms are developer-centric, some designer-centric. So from project to project the input we get can be completely different.

        It depends on the source. Some designers just give us PSDs, I’ve even had designers give me mocks in Powerpoint and Excel. Other designers however may present us with full HTML, have predefined brand standards including an existing pattern library to draw from. Some designers span the gap between designer and developer and can be very specific about the implementation. Especially if that designer is used to having some amount of control over their content using a CMS or tools like Test and Target where they can swap out content and measure user interaction from content changes.

        0
        • 26

          Okay that makes sense… in a way… I guess :) I don’t have experience in these kind of design/development situations, so it is kinda new to me that designers (that don’t code) are busy with class naming convention while designing. Thanks for your clarification!

          0
    • 27

      They should work in tandem for the most part. You make it sound as if the two are separated from each other and incapable of conversing. For starters, the developers (front-end) choosing class names should have enough foresight that class names should never have to change. Things should be named intelligently enough that if the brand color or font changes, or a new section is added, that new or existing classes won’t require changing in terms of naming.

      Again though – it boils down to: if your designers have to change a class, why aren’t they telling the other developers or why don’t they know that this could happen? Seems like a communication issue more than anything.

      As an addendum – for things like hiding, showing, etc. my company uses a set of commonly used classes/mixins for this purpose. We have is-hidden, is-shown, ir (image replacement), fl (float left), fr (float right), cf (clearfix), etc. all for use in the HTML/jQuery. Another thing to keep in mind is to remove jQuery functionality from styling. So if your call-to-action button has to slide in put the classes “primary-btn” and “js-slide-left” on it. This allows your front-end devs to style the button with “primary-btn” and the back-end to hook the item to jQuery using the “js-slide-left”.

      0
      • 28

        In some cases yes, they are separated from one another. We might have a design team that’s provided a design and completed their work and offshore developers coming in well after to implement said design. Even when the teams are working in parallel there can be big gaps in communication due to location, language, corporate culture, perceived ownership etc.,.

        I guess what I’m asking is, aside from “communicate better”, are there more technical ways to let the developers/designers know that the class they are working with is in use by JS. Even if this technical twist requires some small amount of documentation. For instance, if a class is manipulated via JS do we add a “js” prefix/suffix to the class to let future developers and designers know that if they update the CSS they also have to look into the JS as well. The other option is just telling developers and designers “if you rename a class/id make sure to check all the JS files too”, with regular verbal reminders and possible beatings with a stick.

        0
        • 29

          You don’t “add js-” you put it there with the intention of using it as a jQuery hook completely separate from the visual styles. A developer (front or back) or a designer can do this and it keeps the two (styling / function) separate while allowing things to change on both fronts without impacting each other.

          0
    • 30

      Hi nhavar, This kind of sounds like a point of communication on a team. I kind of talk about this in the “Web team” section of the article. Shoot me a tweet or something if you want talk further!

      0
    • 32

      Choosing some common coding standards can help alleviate this problem. It’s easier when designers and devs (and folks who are somewhere between!) can all speak the same language.

      For example, the SMACCS style guide recommends prefacing JavaScript-driven classes with “is” – for example, “.is-hidden”. That way, it’s clear that the class refers to a state and is probably hooked into JavaScript somewhere.

      Beyond that, close communication is really important. Nothing is worse than having two people change one line of code back and forth five times before either one notices the commit message that says, “Hey, don’t change this!”

      Finally, most IDEs and text editors come with a “find in project” function. Whenever I change a class name, I search for the class across any files – CSS, JavaScript, PHP – to make sure I’ve caught every instance of the class.

      0
  6. 33

    Your transitionend detection will fail in Firefox and Opera. In the Modernizr docs we have outlined how to correctly bind to the transitionend event, even when browsers kill the prefixes on their events: http://modernizr.com/docs/#prefixed

    0
  7. 34

    Great read, loved the premise.

    0
  8. 35

    I agree with the goals of this article. But not in all cases. Turning those style classes on and off is often only possible with use of JavaScript, which means that the feature will not work without JavaScript anyways, breaking the progressive enhancement flow. Probably easier and better add style inline (i.e. .hide()) than to create separate class in css, which could possibly snowball into a huge document that is to bring down the speed of the site.

    Moreover, there is very little ROI in trying to make all of the DOM elements look great. Good coding style is to make sure the source looks good, but if elements have inline classes attached to them by JS, so be it. There has to be balance struck and I think it’s important to keep the goals of this article in mind, but code efficiently and for all (or at least most) browsers. Let’s remember that we make web pages first for users, and only second for ourselves to fix and change later.

    0
  9. 36

    I agree with the entire article. I consider that nowadays we should keep the dependency between JS and CSS as low as possible. Trying to keep them completely separate it will result into a save of time and money[for clients] in the future. As designers and developers we do our job, but we never know who’s going to be our next employer. Of course, it may happen that we’ll get a completely messed-up JS and CSS code. This case won’t actually cancel what I said before, because it may easily result into a challenge for us: low-dependency between JS and CSS. It may also result into a high-quality review so that there can easily be established a better relationship between designer/developer and employer.

    0
  10. 37

    I think it’s well past its due time for us to get together and march to the homes of the top 5 browsers:

    Chrome
    Firefox
    Safari
    Opera
    Interne…..don’t make me say it.

    And DEMAND 1 DOM, and complete adherence to W3C standards and technology.

    Standardization before Deviation! …I’m just so freaking sick and TIRED of having to deal with the idiosyncrasies of browser differences. If desktop vs tablet vs mobile design wasn’t enough, we are ever-tasked with having to check the work against a myriad of environmental combinations between these browsers… All it means in the end is a mass of time and effort to get a product to just work as intended.

    Everyone and their grandmother wants to make the next big thing, and some definitely move us in the right direction, but this core segregation seems to now and forever be the Web Developer’s undying arch-nemesis.

    0
  11. 39

    I agree completely.

    Although unfortunately given the choice of using libraries/plugins that work, but do things the ‘wrong’ way and trying to roll your own the ‘right’ way, invariably the former will win.

    With CSS3 however, much of the work that used to be done in JS/JQuery can be done via the new CSS Selectors, Transitions, and Animations, and in most cases is easier to implement. This means the additional cost of the CSS3+fallback solution is often fairly neglibile as you have shown, and it is only the more complex plugins that will be difficult to reimplement.

    0
  12. 40

    Hi I am a wordpress developer, Im having a critical issue with few wordpress themes which comes with CSS & JAVA together & which affects to some widgets… Please tell me a solution.

    Thanks & regards
    Kelly
    WordPress Hosting

    0
  13. 41

    Love the article and I completely get your point. You mentioned at some point, that people argued with you about those classes used for js getting lost in the dev-process. I use a pretty simple solution for that, that works without any communication:
    Elements are only and I mean ONLY selected by data-attributes. This way classes and IDs can be changed without thinking of breaking any JS. Plus… All classes used in JS for applying styles to elements have a js- prefix. That way everybody knows that this class is used somewhere in the JS.

    0
  14. 42

    Here is an example of how to work with vendor-prefixed CSS properties via jQuery. I would rather use cssHooks (http://api.jquery.com/jQuery.cssHooks/).

    0
  15. 43

    Great article, going to be remembering some of these pointers.

    0
  16. 44

    The great thing about HTML5 is that it finally allows developers to REALLY separate Logic from Presentation from Content… borderline MVC stuff right out of the box.

    However, as long as developers are relying primarily on element selectors and dynamic HTML (.innerHTML+=”) for Javascript, code will remain as hard to maintain as it was ten years ago.

    For those of you attached at the hip with JQuery (or another DOM-heavy library), please do us future site maintainers a favor, and use $(“#id”) selectors only when necessary, preferably in one place. That way, if the page changes a bit, we won’t need to edit hundreds of lines of code and hope everything blows over. Remember, Javascript for logic.

    0
  17. 45

    Gunnar Bittersmann

    November 21, 2012 6:15 am

    Once .on(‘click’, …), twice .addEventListener(transitionend, …); seriously? Either write plain JavaScript or use jQuery, but don’t mix! Don’t give such examples of sloppy programming in articles, please!

    It should be a safe assumption that browsers not capable of CSS transitions run on older, i.e. slower hardware. Each added JavaScript might slow down the system even more, and the JavaScript animation would be bumpy. Hence the better fallback for a CSS transition might be no transition.

    0
  18. 46

    Your example.. Using Behavioral CSS With JavaScript Fallbacks… that could packaged. Beeback.js?, backstyle? Stylefall? Stylebee? Darn, styleback is already an ad-bucket domain…

    0
  19. 47

    Gunnar Bittersmann

    November 22, 2012 1:04 am

    Once .on(‘click’, …), twice .addEventListener(transitionend, …)? Seriously? Either write plain JavaScript or use jQuery, but don’t mix! Don’t give such examples of sloppy programming in articles, please!

    It should be a safe assumption that browsers not capable of CSS transitions run on older, i.e. slower hardware. Each added JavaScript would slow down the system even more, and the JavaScript animation would be bumpy. Hence the better fallback for a CSS transition might be no transition.

    0
    • 48

      Safe to assume than, per exemple, an IE9 computer runs on older hardware ?
      Not at all.
      Moreover IE9 has excellent JS perfs.

      0
  20. 49

    I like the idea of developing a better approach to connect css with javascript but I’m not quite sold on the approach you offer here, at least not for now with limited support for css3 and the differences between browsers. If I have such a nice frameworks like jQuery and modernizr doing the job of backwards compatibilty for me and which is using css3 animations where possible, why should I do it myself? Like you said, its double the work and thus leads to more code to maintain and in my opinion to less consistency.

    0
    • 50

      Gunnar Bittersmann

      November 23, 2012 1:43 am

      “…because, as we all know, CSS is much lighter than JavaScript in both download and execution time. Being able to offload some of the weight JavaScript carries onto CSS is a great benefit.”

      0
  21. 51

    Gunnar Bittersmann

    November 23, 2012 5:48 am
    .hide {
    	   position: absolute;
    	   top: -9999px;
    	   left: -9999px;
    	}
    

    is not a good idea.

    0
  22. 52

    about the hide() method:
    I didn’t get the argument about the accessibility – if it is hidden from regular users – why should it be readable to users with screen readers? that just doesn’t make any sense…

    0
  23. 53

    Love the premise of this article and what it stands for, however I have to agree with some of the above comments regarding the quality of the examples, ironically they are not that efficient.

    For those asking, here is a nice performance comparison between CSS3 transitions and jQuery animate:

    http://css3.bradshawenterprises.com/blog/jquery-vs-css3-transitions/

    0
  24. 54

    When I started building my first mobile site, I was used to doing much of what this article suggests. I kept my JS and CSS separate and added and removed classes as needed. But I found adding and removing classes to be too slow on mobile devices. Typically the reason for changing styles after a page has loaded is to change the UI on touch events. Immediate user feedback to touches is critical and .addClass(‘hide’) feels like an eternity. In my experience CSS is not always faster.

    And anyway, if you’re already using javascript to add a class, you’re already using javascript…obviously. So why would addClass be lighter or faster than style.display = “none”? It isn’t.

    0
  25. 55

    I agree with the premise of the article, but I don’t understand the purpose of implementing animations in both CSS and Javascript. If the Javascript solution has to be there(because you want to support a browser that can’t handle the cleaner CSS solution) then why bother writing the CSS solution in the first place? It makes the code much more complicated and feels to me like using fancy new features just for the heck of it. What are the advantages of doing it this way? If performance is a deal-breaker with the JS solution then it seems to me that you’re already breaking support for the old browsers(the ones most likely to have performance problems) anyway. I feel that it makes more sense to use the Modernizr check to simply disable the animations in browsers that don’t support the CSS.

    0
  26. 56

    Well information. I will implement it in my joomla template Avatar Simple.

    0
  27. 57

    You mention keeping css out of your javascript…

    but isn’t behavioral css basically putting javascript in your css?

    0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top