Say you've got a menu that toggles open and closed with a button. My standard way of going about this would be to write the CSS for a closed menu, and write Javascript that specifies (or animates to) an open menu state.
Lately I've gotten into Active.js, a client-side MVC framework. It provides for view classes with builders for making DOM fragments, and those fragments can be given methods that handle things like animation and DOM state.
Something feels wonky about describing the initial state in CSS, and then describing alternate states in JavaScript. Without animation, it would be sensible to just do it all in CSS and just use javascript to add or remove DOM classes.
My other idea is to describe all of the states (folded, unfolded, red, green) of a DOM object in JSON (rather than CSS) and give my ActionView object methods for animating between those states. Is anybody doing this? Other ideas?
As far as animation goes, it wouldn't be a violation of DRY to have basic styling in CSS and then the animation or styling you can't achieve in pure CSS in javascript because you still don't have any repetition if done right. If you think its a more "pure" way to do things you can try to keep more of the styling in javascript or CSS, but those are just the languages you are using and if you consider them both expressions of the same underlying DOM its entirely appropriate to use the more expressive or compatible language wherever needed.
I typically take CSS as far as it will go and then start using jQuery to do the things that CSS can't handle or are not cross browser, like animations.
Related
I've been wondering for some time now why should I use Angular animations over CSS animations. I see few areas one might consider before using them:
Performance
In the first step I found this question which deals only with performace side of things. The accepted answer is not satisfying for me because it states that one should use CSS animations wherever possible so that optimizations like running the animations in separate thread can apply. This doesn't seem to be true, because Angular documentation states
Angular animations are built on top of the standard Web Animations API and run natively on browsers that support it.
(emphasis mine)
And when we look at Web Animations API Draft we see that the same optimizations can apply to Web Animations as to CSS specified in sheets.
While it is possible to use ECMAScript to perform animation using requestAnimationFrame [HTML], such animations behave differently to declarative animation in terms of how they are represented in the CSS cascade and the performance optimizations that are possible such as performing the animation on a separate thread. Using the Web Animations programming interface, it is possible to create animations from script that have the same behavior and performance characteristics as declarative animations.
(emphasis mine again)
Apart from some browsers like IE don't support Web Animations, is there any reason to use either CSS declarations over Angular animations or vice versa? I see them as exchangeable performace-wise.
More control over the animations
This might look as an argument for Angular animations, because you can pause animation or use JS variables with it etc., but the same is true while using eg. CSS animation-play-state: pause or using CSS variables specified in JS, see documentation.
Now I can see it might be inconvenient to set the CSS variables in JS code, but the same is true while using Angular animations. These are typically declared in #Component animations field and don't have, except for via the animation state data bound property, access to instance fields (if you don't create your animation via AnimationBuilder of course, which btw is also not very convenient or beautiful either).
Other point is, with Web Animations API it is possible to inspect, debug or test the animations, but I don't see how this is possible with Angular animations. If it is, could you please show me how? If it isn't, I really don't see any advantage of using Angular animations over CSS ones for the sake of control either.
Cleaner code
I've read for example here a paragraph stating that separating animations from "normal" styles is actually separation of behaviour and presentation. Is really declaring animations in styles sheets mixing those responsibilities? I saw that always the other way, especially looking at CSS rules in the #Component animations gave me a feeling of having CSS declarations on one too many places.
So how is it with Angular animations?
Is it just a convenience utility to extract animations away from the rest of the styles, or does it bring anything worthy feature-wise?
Does a usage of Angular animations pay off only in special cases or is it a convention a team chooses to go all the way with it?
I would love to here about tangible advantages of using Angular animations. Thanks guys upfront!
So I did some research and although I didn't find any argument for nor against Angular animations performance-wise (as already stated in the question above), there are very good arguments to use Angular animations feature-wise which should be good enough for purists who want to have CSS only in sheets, at least in certain cases.
Let me list some useful features where each alone makes a convincing case for Angular animations. Most of them can be found in Angular animations documentation:
Transition styles - these styles are only applied during transition from one state to another - only while an element is being animated, and one uses them like this:
transition('stateA => stateB', [style({...}), animate(100)])
Trying to do the same with CSS only might not be as expressive in terms of which previous state led to the next. And it can be outright clunky if the animation has to differ based on the initial state but the end state is the same.
The void state together with :enter and :leave aliases (void documentation, :leave and :enter documentation) - Let you animate elements being added or removed from the DOM.
transition('stateA => void', animate(...))
This is very cool because previously, although it was easy enough to animate the addition, the removal was more complicated and required to trigger animation, wait till its end and only after that remove the element from the DOM, all with JS.
Automatic property calculation '*' (documentation) - Allows for performing traditionally difficult animations like height transitions for elements with dynamic height. This problem required either to set fixed height on element (inflexible), use max-height with tuned transition function (not perfect) or query element's height with JS (potentially causing unnecessary reflows). But now with Angular it is as easy as this:
trigger('collapsible', [
state('expanded', style({ height: '*' })),
state('collapsed', style({ height: '0' })),
transition('expanded <=> collapsed', animate(100))
])
And the animation is smooth and "complete" because the actual height of the element is used for the transition.
Animation callbacks (documentation) - this is something that wasn't possible with CSS animations (if not maybe emulated with setTimeout) and is handy eg. for debugging.
Unlike stated in the question, it is actually possible to use instance fields as params in Angular animations, see this question. I find it much easier to use than manipulating CSS variables through DOM API as shown here on MDN, not mentioning the limited support in some browsers.
If you need any of the features listed above, Angular can be a better tool for the task. Also when there is many animations to manage in a component, and this is just my personal opinion, I find it easier to organize animations the Angular way than have them in sheets, where it is harder too see the relationships between them and various element states.
I've made some code (tool? framework? Not sure what to call it) that is intended to make it possible to style CSS with Javascript but not jump when reloading or changing pages (so for use in traditional multi-page sites... not sure the conventional term for that). I'm no web expert so am unsure if it's worth developing this further or if there's better solutions to what I'm trying to solve (more than likely).
The basic structure is
A. Under certain client-side conditions (e.g. browser resolution, but could be anything, like a certain user using the site), CSS is generated by client-side JS, written to a file on the server under the appropriate heading relative to scenario (e.g., 1024x768.css, 102400x76800.css).
B. The server code checks (via cookies) if client-side condition is met, checks if css file pertaining to condition exists, uses it, otherwise generates it (A.)
Potential uses
You inherit a legacy site or clients insist on a certain template (Wordpress theme), with predetermined HTML structure, such that it's difficult to achieve a custom look just modifying the CSS. It might be much quicker to make calculations and adjustments with Javascript than refactor the HTML or figure out the solution in CSS (time permitting the ideal solutions, arguably). On the other hand, you don't want the style to jump every time you load the page since that looks tacky.
Edit: example of the above
As noted below in the comments, I can't think of a great example off the top of the ol' noggin. Right now my test is modifying a navigation menu of the type <div class="menu"><ul><li><a>Section 1</a></li><li><a>Section n</a></li></ul></div> such that the <a>'s have just enough padding on both sides that the menu <div> fully fills up the width of the browser.
I imagine there's a conventional solution to this, so if you're feeling in the mood, please let me know.
You want particularly complicated sizing, positioning based on complex calculations (dependent on screen size, or not), but, again don't want things jumping around.
Edit: example of the above
Positioning elements in a spiral pattern (say this kind) with diminishing size. This seems to be nontrivial in CSS, perhaps done by calculating the positions beforehand and placing with absolute positioning. But then there's the problem of having everything scale depending on screen resolution.
Alternately Javascript could calculate positions and sizes dynamically. Of course writing the method to correspond to the mathematical spiral function would be a challenge (though an interesting one).
There could be other solutions like using .svg, but if written generically it would be possible to position according to other mathematical functions (e.g., sine wave), or complex ratios (golden mean) fairly easily.
You want a site where the user can customize the look (reposition or even resize elements) and you want the customization to automatically get remembered and generated in the server-side code (perhaps even without a login). I'm sure this is facilitated by many frameworks, but this kind of divests the process from a specific framework.
I was wondering if other folks had thoughts on whether:
A. There's a better solution to all this I've missed.
B. The system I described of pushing CSS from JS to be written on server sounds sound, or if the same thing could be achieved another way entirely client-side.
C. And I guess since it's not a specific technical question whether this is the right place to ask this question, and if not, where I should.
Like I said, I'm no expert, so would greatly appreciate any feedback or other things that might help me to learn.
Thanks
While I understand that Angular 2's animate is primarily used to animate the transition between states in a fixed time, this is not always what is most convenient.
In my case, I have a slide-able element, that I wish to animate based on how far I have moved it from its default position. That is, I want to provide the handler dynamically with, for example a float number between 0 and 1 representing how far along the animation I should be. Can the angular 2 framework handle this? Can I perhaps, somehow, bypass the default animate(time) property, and directly call the underlying function that changes the css?
I'm not 100% clear on your problem, but I don't think what you're asking for is possible with Angular animations. Angular's animations are built on top of the Web Animation API, which itself is just a streamlined means of interacting with CSS Animations. CSS animations are defined with keyframes + durations (see https://css-tricks.com/almanac/properties/a/animation/).
Theoretically, you could create a complex set of keyframes that you "stepped through" based on the position of your slide-able element, but it would be a hack and not really what you're asking for.
To accomplish your goal, I think you'll need to use custom Javascript or find an outside library to help you. You're a little vague on the project details, but, as an example, a library like Tether might help you.
I ran into this beautiful UI mockup on Behance and am very curious about the best way to implement this.
https://www.behance.net/gallery/25264659/Google-transitions
Essentially, I would like my search bar and logo to animate up to the top exactly like this after the form (aka the text input) has been submitted.
My app is an Angular app, so would it be more practical to create an Angular directive? Or implement this with pure CSS or JQuery (independent from Angular)?
Your animation will be independent of AngularJS. In regards to performance of the animation JQuery is by far the absolute slowest. The standard would be to use CSS transitions / animations. If you are not comfortable with CSS then user something like velocity.js. It has a syntax similar to JQuery but used window.requestAnimationFrame making it potentially even faster then CSS.
All Angular would be used for would be used for would be to call the animation or add / remove a class to cause the CSS transition to animation when the search is underway.
As for the animation itself I unfortunately cannot help much with, those things tend to take a lot of effort to get looking good.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm working on a responsive design would like to know if it is better to style an element using JavaScript or with CSS? CSS is certainly easier to maintain, I won't argue that, but I'm a lot more comfortable building an object in JavaScript. Maybe I'm making more work for myself than I should, but I feel like I have more control overall and I like being able to hook into every object on the screen.
I have constructors that generate the entire page layout and push it into the DOM. No images, just pure JavaScript styling and SVG icons.
What I would like to know is:
What performs better?
What, if any hardware support is there for JS or CSS?
Is a pure JavaScript solution better than using CSS Calc()?
What's more portable?
What's more forward compatible?
I tend to avoid jQuery as I'm more interested in learning what makes things work right now, so pure JavaScript and CSS3 only, please.
Your styling should be done using CSS wherever possible. Have different classes setup according to your needs, then add or remove classes when absolutely necessary with JS.
One thing to keep in mind is that changing styling via JS is a one-time change. Elements added dynamically VIA Ajax won't inherit the styling changes automatically. Another good reason to stick with CSS.
See this post for additional confirmation Should I load responsive design via JS or CSS
As suggested in the link
Putting everything regarding styles in the CSS files is the best
practice.
HTML => Structure
CSS => Styles
JS => Logic
CSS is the best way to style an (X)HTML document.
Even if you need to style a document by using raw JavaScript or DOM, or some framework like jQuery, it'll mean you're giving values to CSS rules.
The rule should be:
Use pure CSS when you can style a predictable document - also you can
enhance your CSS and use CSS selectors for generalized or complex
scenarios -.
Use JavaScript/DOM or frameworks like JavaScript when document or portions of it aren't predictable or are created on-the-fly and
you're applying special effects like fades or any other - in fact,
CSS 3.0 has transitions so it's possible to do a lot of things
without JavaScript -.
After all, think how simpler can be things done with CSS and what kind of overkill is using JavaScript instead, and keep in mind its cons (a very important point: browser compatibility and performance).
The more CSS you use, the more standarized, cross-browser, performant and maintainable web.
UI should be left to UI solutions (HTML/CSS). JavaScript should only provide additional functionality.
To supplement this (because you mention CSS3) if you're referring to animations and new additions to CSS3 (that may not otherwise be available) you can use javascript--but only as a fallback. (e.g. using jQuery's fadeTo over creating an animation timeline with CSS3).
There are serious drawbacks when applying styles with JavaScript, not only because you have no control over specificity, it is slow (as you'd expect), any .css() calls involving classes, e.g. $('.something').css(...), will apply css to only elements of that class that exist at the time, not .somethings created in the future.