I want to implement feedback on a div when the user click on it. The div will quickly fade to another color and then back to its original color again.
My first option is to use a spritesheet, where I will change the background position property of the div.
Part of the implementation looks like this:
pos = 0;
function fadeAction(el){
if (pos != 100){
pos += 10;
$(el).css("background-position","0% "+pos+"%");
setTimeout(function(){fadeAction(el);},10);
}else
pos=0;
}
My second option is to change the background color according to an array of colors:
colors = ["#FF00FF","#443322", etc];
i = 0;
function fadeAction(el){
if (pos != 10){
i += 1;
$(el).css("background-color",colors[i]);
setTimeout(function(){fadeAction(el);},10);
}else
i=0;
}
My third option (which will be scrapped due to device incompatiblity) is to use jquery.color.
function fadeAction(el){
$(el).css("background-color",fadeColor);
$(el).animate({
backgroundColor: "#E9E9E9"
}, 150 );
}
Which of these two methods (scrapping the third) will we the most efficient? There will be multiple buttons (div) on the page that will use this function and it will primarily be used on mobile devices with webkit browsers.
Best performance is achieved with CSS3. This because it browser uses hardware acceleration.
EDIT: I was wrong (thanx Zougen Moriver) it isn't automatically triggered (see comment) but it has still better performance over the javascript solutions.
Here is an example:
.test {
height: 100px;
width: 100px;
background-color: #eee;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
.test:hover {
background-color: #fc3;
}
http://jsfiddle.net/Vandeplas/LZNZb/
I used hover because it doesn't need javascript, but if you change the color (via javascript, by adding a class or changing the style) it will fade to that color.
The downside is that it isn't supported on legacy browsers..
Here is an example using on click handler:
$('.test').on('click', function() {
$(this).css('background-color', 'green');
//$(this).addClass('otherColor');
});
http://jsfiddle.net/Vandeplas/LZNZb/1/
As you can see I commented out the other option using the class... both will work...
If you're just changing plains colours, the CSS style option will be more efficient than spritesheets. There will be no need for the browser to make an additional HTTP request for your spritesheet, and using CSS transitions you will be able to fade between the colours.
There will also be one less resource in the device's memory.
To transition the colour, apply this CSS:
.yourElement {
-webkit-transition: color 150ms;
transition: color 150ms;
}
..And continue using your JavaScript to toggle the colour changes on click.
Related
As jQuery.fadeIn is not very smooth on mobile devices I try to use CSS but it doesn't work as expected. How to create a smooth CSS animation using Javascript?
In general this is what I'm trying:
$('div')
.css('opacity', 0) // at first, set it transparent
.css('display', 'block') // make it appear
.css('transition', 'opacity 1000ms linear') // set a transition
.css('opacity', 1); // let it fade in
https://jsfiddle.net/8xa89y04/
EDIT1:
I'm not searching a solution using static CSS classes. The point is: I need to set this dynamically in Javascript code - a replacement for jQuerys fadeIn() for example.
Your logic isn't quite right. Firstly you cannot animate display, so to achieve what you require the element has to always be rendered in the DOM (ie. anything but display: none). Secondly, the transition property should be placed within the CSS styling itself. Finally you can make this much more simple by setting all the rules in CSS classes and just turning the class on/off. Try this:
div {
position: absolute;
width: 100px;
height: 100px;
background-color: black;
opacity: 0;
transition: opacity 1000ms linear;
}
.foo {
opacity: 1;
}
$('div').addClass('foo');
Working example
Use this code.
CSS
div {
width: 100px;
height: 100px;
background-color: black;
transition:opacity 2s;
}
JavaScript
$('div').hover(function(){
$(this).css('opacity','0');
})
Without using CSS properly, you are going the long way about it. You'll need to emulate what you would normally do in CSS, using JavaScript, so you'll be setting all your CSS properties, transitions etc, then applying them with js.
I can't personally see any benefit in doing this. Using actual CSS would be cleaner, more efficient, more maintainable, and simply a plain better solution to what you need.
I think this is what you are looking for.
$('div').css({"display":"block", "opacity":"0"}) //Make div visible and opacity as "0"
$('div').animate({opacity :1}, 1000); //Animate div to opacity "1"
Take a look at this Demo
Found the cause here: CSS transitions do not work when assigned trough JavaScript
To give this attention I need to give the browser some time - or better: a working slot to activate the transition as the time seems not to be a problem.
The following code cuts the process in two by using setTimeout()... and it works!
var div = $('div');
// first process
div
.css('opacity', 0) // initial opacity
.css('display', 'block') // make it appear (but still transparent)
.css('transition', 'opacity 1s linear'); // set up a transition for opacity
// break - start the transition in a new "thread" by using setTimeout()
window.setTimeout(function(){
div.css('opacity', 1); // start fade in
}, 1); // on my desktop browser only 1ms is enough but this
// may depend on the device performance
// maybe we need a bigger timeout on mobile devices
I have an animation which runs on any new item to a grid. Lets say this animation takes 5 seconds to run. Currently, if I try removing that element within the 5 seconds (so whilst the enter animation is still running), the item remains in the list until the enter animation finishes.
Looking at the docs, it says that this is by design:
You'll notice that when you try to remove an item
ReactCSSTransitionGroup keeps it in the DOM. If you're using an
unminified build of React with add-ons you'll see a warning that React
was expecting an animation or transition to occur. That's because
ReactCSSTransitionGroup keeps your DOM elements on the page until the
animation completes.
It ways that you need to add the following (updated to the relevant class names obviously) and it should work for the case described above:
.example-leave {
opacity: 1;
transition: opacity .5s ease-in;
}
.example-leave.example-leave-active {
opacity: 0.01;
}
I'm not finding this to be the case, even though I have the described leave classes, I'm finding that it is still waiting for the original enter animation to finish, is this behavior correct, how do I fix this?
Here is a video showing the quirk in question - https://www.youtube.com/watch?v=3oKerWlLZIE
If it makes a difference here is my classes:
.request-summary-item-holder-enter {
background-color: #F8F5EC;
transition: background-color 5s ease-in;
}
.request-summary-item-holder-enter.request-summary-item-holder-enter-active {
background-color: transparent;
}
.request-summary-item-holder-leave {
opacity: 1;
transition: opacity 0.05s ease-in;
}
.request-summary-item-holder-leave.request-summary-item-holder-leave-active {
opacity: 0.01;
}
Update:
Source code references:
Setting the state - https://github.com/avanderhoorn/Glimpse.Client.Prototype/blob/master/src/request/components/request-summary-view.jsx#L33
Usage of transition group and setting keys - https://github.com/avanderhoorn/Glimpse.Client.Prototype/blob/master/src/request/components/request-summary-list-view.jsx
I'm trying to animate some elements on my page. One of the properties I need to animate is bottom, however, I also need to be able to reposition the element without it animating, that's why I added a seperate class to it: .anim
.slideshow_footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
color: #fff
}
.slideshow_footer.anim {
-webkit-transition:bottom 0.3s ease-out;
-moz-transition:bottom 0.3s ease-out;
-o-transition:bottom 0.3s ease-out;
-ms-transition:bottom 0.3s ease-out;
transition:bottom 0.3s ease-out;
}
In my Javascript, I do the following:
var footer = $('#footer');
// do some magic with the footer
// ...
// ...
setCss(footer, 'bottom', -100); // position it so it's hidden, this should be immediate
addClass(footer, 'anim'); // add the animation class
setCss(footer, 'bottom', ); // animate the footer sliding in
Note that I'm not using jQuery or anything, it's an inhouse javascript framework.
I have found a workaround that solves the problem, but it's extremely ugly:
var footer = $('#footer');
// do some magic with the footer
// ...
// ...
setCss(footer, 'bottom', -100); // position it so it's hidden, this should be immediate
addClass(footer, 'anim'); // add the animation class
setTimeout(function() {
setCss(footer, 'bottom', ); // animate the footer sliding in
}, 0); // even no timeout works...
Can anyone explain to me what is happening and how this should best be solved? Possibly changing the addClass and setCss functions?
To answer my own question:
Using a timeOut is the correct approach.
The browser doesn't update the visible HTML until the entire JavaScript is done. If it did, setting "right" after "bottom" would move the element twice. From the perspective of the browser, the element instantly gains both "anim" and bottom 0. setTimeout with 0 timeout tells the browser to execute the code as soon as possible, but not in the same round of JavaScript.
The workaround is actually adopted by many people as an "asynchronous" way to run codes
I have a DOM element with this effect applied:
#elem {
transition: height 0.4s ease;
}
I am writing a jQuery plugin that is resizing this element, I need to disable these effects temporarily so I can resize it smoothly.
What is the most elegant way of disabling these effects temporarily (and then re-enabling them), given they may be applied from parents or may not be applied at all.
Short Answer
Use this CSS:
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
Plus either this JS (without jQuery)...
someElement.classList.add('notransition'); // Disable transitions
doWhateverCssChangesYouWant(someElement);
someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes
someElement.classList.remove('notransition'); // Re-enable transitions
Or this JS with jQuery...
$someElement.addClass('notransition'); // Disable transitions
doWhateverCssChangesYouWant($someElement);
$someElement[0].offsetHeight; // Trigger a reflow, flushing the CSS changes
$someElement.removeClass('notransition'); // Re-enable transitions
... or equivalent code using whatever other library or framework you're working with.
Explanation
This is actually a fairly subtle problem.
First up, you probably want to create a 'notransition' class that you can apply to elements to set their *-transition CSS attributes to none. For instance:
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
Some minor remarks on the CSS before moving on:
These days you may not want to bother with the vendor-prefixed properties like -webkit-transition, or may have a CSS preprocessor that will add them for you. Specifying them manually was the right thing to do for most webapps when I first posted this answer in 2013, but as of 2023, per https://caniuse.com/mdn-css_properties_transition, only about 0.4% of users in the world are still using a browser that supports only a vendor-prefixed version of transition.
There's no such thing as -ms-transition. The first version of Internet Explorer to support transitions at all was IE 10, which supported them unprefixed.
This answer assumes that !important is enough to let this rule override your existing styles. But if you're already using !important on some of your transition rules, that might not work. In that case, you might need to instead do someElement.style.setProperty("transition", "none", "important") to disable the transitions (and figure out yourself how to revert that change).
Anyway, when you come to try and use this class, you'll run into a trap. The trap is that code like this won't work the way you might naively expect:
// Don't do things this way! It doesn't work!
someElement.classList.add('notransition')
someElement.style.height = '50px' // just an example; could be any CSS change
someElement.classList.remove('notransition')
Naively, you might think that the change in height won't be animated, because it happens while the 'notransition' class is applied. In reality, though, it will be animated, at least in all modern browsers I've tried. The problem is that the browser is buffering the styling changes that it needs to make until the JavaScript has finished executing, and then making all the changes in a single "reflow". As a result, it does a reflow where there is no net change to whether or not transitions are enabled, but there is a net change to the height. Consequently, it animates the height change.
You might think a reasonable and clean way to get around this would be to wrap the removal of the 'notransition' class in a 1ms timeout, like this:
// Don't do things this way! It STILL doesn't work!
someElement.classList.add('notransition')
someElement.style.height = '50px' // just an example; could be any CSS change
setTimeout(function () {someElement.classList.remove('notransition')}, 1);
but this doesn't reliably work either. I wasn't able to make the above code break in WebKit browsers, but on Firefox (on both slow and fast machines) you'll sometimes (seemingly at random) get the same behaviour as using the naive approach. I guess the reason for this is that it's possible for the JavaScript execution to be slow enough that the timeout function is waiting to execute by the time the browser is idle and would otherwise be thinking about doing an opportunistic reflow, and if that scenario happens, Firefox executes the queued function before the reflow.
The only solution I've found to the problem is to force a reflow of the element, flushing the CSS changes made to it, before removing the 'notransition' class. There are various ways to do this - see here for some. The closest thing there is to a 'standard' way of doing this is to read the offsetHeight property of the element.
One solution that actually works, then, is
someElement.classList.add('notransition'); // Disable transitions
doWhateverCssChangesYouWant(someElement);
someElement.offsetHeight; // Trigger a reflow, flushing the CSS changes
someElement.classList.remove('notransition'); // Re-enable transitions
Here's a JS fiddle that illustrates the three possible approaches I've described here (both the one successful approach and the two unsuccessful ones):
http://jsfiddle.net/2uVAA/131/
Add an additional CSS class that blocks the transition, and then remove it to return to the previous state. This make both CSS and JQuery code short, simple and well understandable.
CSS:
.notransition {
transition: none !important;
}
Note: !important was added to be sure that this rule will have higher preference, because using an ID is more specific than class.
JQuery:
$('#elem').addClass('notransition'); // to remove transition
$('#elem').removeClass('notransition'); // to return to previouse transition
I would advocate disabling animation as suggested by DaneSoul, but making the switch global:
/*kill the transitions on any descendant elements of .notransition*/
.notransition * {
transition: none !important;
}
.notransition can be then applied to the body element, effectively overriding any transition animation on the page:
$('body').toggleClass('notransition');
For a pure JS solution (no CSS classes), just set the transition to 'none'. To restore the transition as specified in the CSS, set the transition to an empty string.
// Remove the transition
elem.style.transition = 'none';
// Restore the transition
elem.style.transition = '';
If you're using vendor prefixes, you'll need to set those too.
elem.style.webkitTransition = 'none'
You can disable animation, transition, transforms for all of element in page with this CSS code:
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '* {' +
' transition-property: none !important;' +
' transform: none !important;' +
' animation: none !important;}';
document.getElementsByTagName('head')[0].appendChild(style);
I think you could create a separate CSS class that you can use in these cases:
.disable-transition {
transition: none;
}
Then in jQuery you would toggle the class like so:
$('#<your-element>').addClass('disable-transition');
If you want a simple no-jquery solution to prevent all transitions:
Add this CSS:
body.no-transition * {
transition: none !important;
}
And then in your js:
document.body.classList.add("no-transition");
// do your work, and then either immediately remove the class:
document.body.classList.remove("no-transition");
// or, if browser rendering takes longer and you need to wait until a paint or two:
setTimeout(() => document.body.classList.remove("no-transition"), 1);
// (try changing 1 to a larger value if the transition is still applying)
This is the workaround that worked easily for me. It isn't direct answer to the question but still may help someone.
Rather than creating notransition class which was supposed to cancel the transition
.notransition {
-webkit-transition: none !important;
-moz-transition: none !important;
-o-transition: none !important;
transition: none !important;
}
I created moveTransition class
.moveTransition {
-webkit-transition: left 3s, top 3s;
-moz-transition: left 3s, top 3s;
-o-transition: left 3s, top 3s;
transition: left 3s, top 3s;
}
Then I added this class to element with js
element.classList.add("moveTransition")
And later in setTimeout, I removed it
element.classList.remove("moveTransition")
I wasn't able to test it in different browsers but in chrome it works perfectly
If you want to remove CSS transitions, transformations and animations from the current webpage you can just execute this little script I wrote (inside your browsers console):
let filePath = "https://dl.dropboxusercontent.com/s/ep1nzckmvgjq7jr/remove_transitions_from_page.css";
let html = `<link rel="stylesheet" type="text/css" href="${filePath}">`;
document.querySelector("html > head").insertAdjacentHTML("beforeend", html);
It uses vanillaJS to load this css-file. Heres also a github repo in case you want to use this in the context of a scraper (Ruby-Selenium): remove-CSS-animations-repo
does
$('#elem').css('-webkit-transition','none !important');
in your js kill it?
obviously repeat for each.
I'd have a class in your CSS like this:
.no-transition {
-webkit-transition: none;
-moz-transition: none;
-o-transition: none;
-ms-transition: none;
transition: none;
}
and then in your jQuery:
$('#elem').addClass('no-transition'); //will disable it
$('#elem').removeClass('no-transition'); //will enable it
If you go to google.com, you notice the menu on top slowly appears once you have mouse over the page. I was wondering what does Google use to control the fading effect?
[edit] since I don't use jQuery, I don't want to include it just to use this feature
There are two ways.
Javascript
Works in most browsers.
Gradually change the CSS opacity attribute of an element using Javascript. That's easiest with a good framework like jQuery, but is quite simple to do yourself.
function fadeIn() {
var element = document.getElementById("someID");
var newOpacity = element.style.opacity + 0.05;
element.style.opacity = newOpacity;
if (newOpacity < 1) {
window.setTimeout(fadeIn, 50);
}
}
Pure CSS
Only supported in Webkit at the moment.
#someID {
opacity:0;
-webkit-transition: opacity 1s linear;
}
#someID:hover {
opacity:1;
}
For an example have a look at the Surfin' Safari blog.
You could use jQuery and add an onmousemove callback on the tag that fades a hidden div with id "mymenu" in, something like:
$("html").one("mousemove", function() {
$("#mymenu").fadeIn("slow")
});
Warning: this was typed here, so I dunno if it compiles ootb.
I've never looked at it, but it's only logical to assume that there's a timer that gets started at load time for the page, and that adjusts either the alpha for the specified element or the opacity of another element that overlays it, in that element's CSS. Every timer tick, the numbers get turned up/down a little and the text becomes a bit more legible. When full visibility is reached, the timer is turned off.
JQuery is a finished, ready to use implementation of this in a cross-platform compatible package. You just add it, stir it up and it's done.
If you choose not to take the advice of the other answers, you'll have to research and implement the strategy from my top paragraph on your own. Good luck!
This is actually a rather complex thing to do because of the cross browser differences. The basics are something like the following:
Get the current opactity of the element as float.
Determine the ending opacity as float.
Determine your rate speed - i dont know what this should be in raw terms - somthing like .01/ms maybe?
Use a setInterval to fire a function that increases the opacity by your rate where: setInterval(function(){myElement.style.opacity = parseFloat(myElement.style.opacity)+0.01;}, 1); Somewhere in ther though you need to check if youve reached the endpoint of your animation and shutdown your interval.
I would think that they set the initial opacity of the elements other than the search box to zero. When the mouseover event is fired, the elements' opacity is gradually increased to 1.
Edit: In code it would look something like this:
var hiddenStuff = document.getElementByClassName("hiddenStuff");
var interval=document.setInterval(function() {
for (var i=0; i<hiddenStuff.length;i++){
hiddenStuff[i].style.opacity+=0.1
}
if (hiddenStuff[1].style.opacity===1){
window.clearInterval(interval);
}
}, 100);
You may need to tweak the parameters to get a smooth animation.
#Georg, that example works on Firefox 3.5 too. :-)
Demo: PURE CSS http://jsfiddle.net/6QS2a/1/
</div>
css:
.item {
height:150px;
width:150px;
border-radius:100%;
background:skyblue;
-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-ms-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;
opacity:0.2;
}
.item:hover {
opacity: 1;
}