For example when I copy the link from an answer and access it, a nice block of color appears to highlight the answer and then is fading out. How this is done?
It looks at the hash, selects that answer, and then animates the background color. Either use jQuery UI or add the Colors plugin to be able to animate colors.
This is what the code may look like...
var hash = window.location.hash;
if (hash) {
var answer = $('#answer-' + hash.substr(1)),
originalBackgroundColor = answer.css('backgroundColor');
// This class changes the background colur.
// Best to keep style stuff in the CSS layer.
answer
.addClass('linked')
.animate({
backgroundColor: originalBackgroundColor
}, 1000);
// You may optionally remove the added class
// in the callback of the above animation.
}
Related
I am adding some elements with ajax. For this example, i am adding user comments. When user make new comment, his comment viewing first place and (this is question) I want to add new background animation first comment div. But i know we cant animate color with Jquery. I can use JqueryUI highlight effect. But i cant select new added element. Off course use here delegate() or on().. But my all try failed.
I need help.
Some Code Example;
$("#DoCommentBtn").click(function(){
var UserID = 1,
LookID = 2,
Comment = $("#CommentInput").val(),
CommentType = 0,
PostData = "USERID=" + UserID + "&LOOKID=" + LookID + "&Comment=" + encodeURI(Comment) + "&CommentType=" + CommentType;
$("#CmAnm").fadeIn();
$.ajax({
type:'POST',
url:'ajax.asp?cmd=docomment',
dataType:'html',
data:PostData,
success:function(cevap) {
$("#CmAnm").fadeOut();
$("#CommentsArea").load("ajax.asp?cmd=LoadComments&LOOKID=" + LookID + "&PART=0");
//Now all comments loaded Here I must animate background first div in #CommentsArea Animation Example: Background color blue to white..
}
});
});
But i know we cant animate color with Jquery
I'm not a jquery expert but i'm sure it is possible.
Is this what you're looking for?
$( "#CommentsArea div:first-child" ).animate({ backgroundColor: "#fff"}, 1000);
Should animate the background to white #FFF in 1 second (1000ms)
Docs: jQuery .animate() - jQuery UI .animate()
EDIT:
changed background to backgroundColor
Animation Properties and Values
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality
(For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used)
Docs : JQuery animate()
So what can i do right now ?
I am adding this library;
Jquery.Color
And now jsfiddle example working.
Example Code :
$(".justDiv").animate({ backgroundColor: "#ffffff",width:105 }, 1000);
I have a web page and for internal links I want to emphasis where the visitor jump after clicking on an internal link on current page. It is just like SO's comment or answer notification. First the target's background will be orange then it will smoothly turn back to white.
I could have done this but color change is not smooth.
HTML part
go to section 1
Google
<a name="section1"><a><h3 id="section1">Section 1</h3>
jQuery part
$(function () {
$("a[href^='#']").click(
function () {
var $id = $(this).attr("href");
$($id).css({"background-color":"#cc7733", "transition":"background-color"});
setTimeout(function () {
$($id).css("background-color", "#ffffff");
}, 2500);
});
});
JS Fiddle is here
Transition should have duration and easing.
{"transition":"background-color 0.5s ease"}
NOTE: 0.5s is sample time, change this to your own.
DEMO
The problem is that you're specifying "transition":"background-color" and aren't specifying a time scale. You need to change this to include a time:
..."transition":"background-color 0.2s"
A better way to do it, however, would be to set the transition property on the CSS itself, then use jQuery to give the element a new class:
/* Select any element with a href attribute. */
:link { /* You could use [href], but :link has better browser support */
transition: 2.5s; /* Transition takes 2.5 seconds. */
}
.changedBackground {
background: #fff;
}
$($id).addClass('changedBackground');
This way you keep the styling separate from the JavaScript, allowing you to easily change the style by only modifying the CSS.
You can use .animate() like this
$($id).stop()
.css({"background-color":"#cc7733"},1000)
.animate({"background-color":"#FFF"},1000);
Note: You need to include jQuery UI to your project for animate to work.
DEMO
I am trying to tween / cycle the color of the background of a page while it is clicked.
When the click is lifted, the cycling stops and the background color remains at the last cycled value. When it is clicked again, the process will continue.
Check the example here to see what I am referring to when I say cycle the color http://www.javascript-fx.com/development/colorcycle/spancycle.html
While browsing for solutions I have come across some libraries like JSTween or GSAP, but with my very fragile javascript experience I failed at implementing the examples to suit my need.
Any suggestions on how to do this will be helpful, preferably without any libraries since it will aid more in my understanding of javascript.
I am not looking for exact code, a pseudocode explanation of the process will also be great.
Best,
Andrei
So, Tweening colors is pretty easy with TweenJS or TweenMax (or TweenLite). I'll show this using TweenMax, mostly because the pseudocode is hard when there is no logic to pseudocode. Assume you have a text element:
<p id="text">This is some text to colorize</p>
You can tween the color of the text to red (#f00) over two seconds like this:
var textEl = document.getElementById('text');
TweenMax.to(textEl, 2, {color: '#f00'});
As far as cycling goes, you can send an onComplete handler to the tween, which will fire when the tween finishes. This will cause it to cycle between red and black:
var textEl = document.getElementById('text');
function toRed() {
TweenMax.to(textEl, 2, {color: '#f00', onComplete: toBlack});
}
function toBlack() {
TweenMax.to(textEl, 2, {color: '#000', onComplete: toRed});
}
toRed();
Here is a CodePen showing this in action.
If you want to make this a bit more compact, you can cycle by flipping the colorFrom and colorTo:
function cycle(colorFrom, colorTo) {
TweenMax.to(textEl, 2, {color: colorTo, onComplete: function() {
cycle(colorTo, colorFrom);
}});
}
cycle('#000', '#F00');
Doing the same thing in other tweening libraries becomes VERY similar.
Pseudocode for doing this cycle while tapped might be like this:
ON_CLICK:
ShowCycle = !ShowCycle;
IF ShowCycle
TweenHandle = cycle( RED, BLACK )
ELSE
IF EXISTS TweenHandle
cancelCycle( TweenHandle )
TweenHandle = null
END IF
END IF
I know I can fade in and out divs and elements, but can I animate properties as well?
I thought about this just now when changing background-image property of a certain div. And thought it'd be cool if the background image was faded in as well ;)
Here's the code I'm using to replace background image. But can it be animated?
var originalBG = $('#wrapper').css('background-image');
$('.bggallery_images img').hover(function () {
var newBG = "url('" + $(this).attr('src');
$('#wrapper').css('background-image', newBG);
}, function () {
$('#wrapper').css('background-image', originalBG);
});
jQuery has the animate() method that does exactly that.
Check out the examples in the manual, they should show you everything you need.
JQuery UI is a plug in that extends the animation function to animate color if that's what you're looking to do with the background. Basically if JQuery doesn't do it, there's most likely a library that extends it to have that functionality.
I use the following snippet to make an element's background lightblue, then slowly fade to whiite over 30 seconds:
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "white" }, 30000);
Two questions.
First, instead of fading to white, is there a way to fade opacity to 100%? That way I don't have to change "white" if I choose to change the page's background color?
Second, about once out of every 10 or 15 times, the background stays lightblue and fails to fade to white. I'm using the latest versions of jQuery and the UI core. What could be going wrong?
EDIT: Bounty is for a solution to problem regarding second question.
EDIT2:
Apparently I got downvoted into oblivion because I said I rolled my own solution but didn't show it. My bad. I didn't want to be self-promoting. My code works 100% of the time and doesn't require jQuery. A demonstration and the code can be found at:
http://prettycode.org/2009/07/30/fade-background-color-in-javascript/
For your second question: in my experience this is usually because a Javascript error has occurred somewhere else on the page. Once there is one Javascript exception, the rest of the page stops running Javascript. Try installing Firebug (if you haven't already), then open up the "Console" tab and enable it. Then any javascript errors or exceptions will be printed to the console.
Another thing to try (which kinda contradicts my last statement...) is to disable all your browser plug-ins to see if you can recreate. Sometimes they interfere with scripts on the page (particularly GreaseMonkey.)
If you could provide a sample HTML snippet which reproduces this animation problem it would be a lot easier for us to help you. In the script I have pasted below, I can click it all day, as fast or slow as I like, and it never fails to animate for me.
For the first question: I know you said you'd found a workaround, but the following works for me (even on IE6) so I thought I'd post it, since it may be different from what you were thinking. (Note that setting CSS "opacity" property through jQuery.css() works on IE, whereas IE does not support the "opacity" property directly in CSS.)
<html>
<head>
<style>
body { background-color: #08f; }
#test { background-color: white; width: 100px; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
var myOpacity = 0.125;
$(function(){
$('#test').css('opacity', myOpacity);
$('a').click(function(){
myOpacity = 1.0 - myOpacity;
$('#test').animate({ opacity: myOpacity });
return false;
});
});
</script>
</head>
<body>
<p>Click me</p>
<div id="test">Test</div>
</body></html>
Dont forget the color plugin.
See here
When the color fails to animate to blue you could try to use the callback function to log a message to the console. You can then check that the event actually fired and completed. If it does then you could potentially use two animates. The first one to animate to a halfway house color then the use the callback to animate to white (so you get two bites of the cherry, if the outer fails but completes the callback has a second go)
It would be good if you could try to recreate the issue or give a url of the issue itself.
e.g
$("#" + post.Id).css("background-color", "lightblue")
.animate({ backgroundColor: "#C0D9D9" }, 15000, function(){
$(this).animate({ backgroundColor: "#ffffff" }, 15000)
});
You could always use something like this, avoiding the JQuery animate method entirely.
setTimeout(function() { UpdateBackgroundColor(); }, 10);
UpdateBackgroundColor() {
// Get the element.
// Check it's current background color.
// Move it one step closer to desired goal.
if (!done) {
setTimeout(UpdateBackgroundColor, 10);
}
}
Also, you may be able to remove the "white" coding by reading the background color from the appropriate item (which may involve walking up the tree).
It is possible to have jQuery change the Opacity CSS property of an item (as mentioned in another answer), but there's two reasons why that wouldn't work for your scenario. Firstly, making something "100% opaque" is fully visible. If the item didn't have any other modifications to its opacity, the default opacity is 100%, and there would be no change, so I'm guessing you meant fading to 0% opacity, which would be disappearing. This would get rid of the light blue background, but also the text on top of it, which I don't think was your intent.
A potentially easy fix for your situation is to change the color word "white" to "transparent" in your original code listing. The color plugin may not recognize that color word (haven't checked documentation on that yet), but setting the background color to "transparent" will let whatever color behind it (page background, if nothing else) shine through, and will self-update if you change your page background.
I'll answer your first question.
You can animate opacity like this:
.animate({opacity: 1.0}, 3000)
I think you can try using fadeOut/fadeIn too..
What about:
$("#" + post.Id).fadeIn( "slow" );
You could possibly have two divs that occupy the same space (using position: absolute; and position: relative; setting the z-index on one higher to make sure one is above and the other is below. the top one would have a transparent background and the one below would have a background color. then just fadeout the one below.
As for the second question:
If you think the default animation classes from JQuery are not properly working you could try Bernie's Better Animation Class. I have some good experiences with that library.
Animate only works for numbers. See the jquery docs. You can do opacity but you can't do background color. You can use the color plug in. Background-color uses strings like 'red', 'blue', '#493054' etc... which are not numbers.