How to use css method of rotation in jquery - javascript

When my webpage is first loaded, my starting div rotates using this CSS code:
#keyframes rotate
{
from { transform:rotate(0deg);
-ms-transform:rotate(0deg);
-webkit-transform:rotate(0deg); }
to { transform:rotate(360deg);
-ms-transform:rotate(360deg);
-webkit-transform:rotate(360deg); }
}
#-webkit-keyframes rotate
{
from { transform:rotate(0deg);
-ms-transform:rotate(0deg);
-webkit-transform:rotate(0deg); }
to { transform:rotate(360deg);
-ms-transform:rotate(360deg);
-webkit-transform:rotate(360deg); }
}
After the rotation, this code is useless.
I would like it so when a button is clicked, it will make this rotation again.
To do this I need to be able to put this css code into a javascript/jQuery function so I can call it at any time.
Is this possible?

TRY THIS
$({deg: 0}).animate({deg: d}, {
duration: 2000,
step: function(now){
elem.css({
transform: "rotate(" + now + "deg)"
});
}
});
Look at JSFIDDLE DEMO

You can wrap your animation behavior into a class like:
.rotate{
-webkit-animation: rotate 4s;
/* more prefixes if you want to */
animation: rotate 4s;
}
Then you can apply that class on click of your button like:
$('#myButton').click(function(){
$('#myElementToAnimate').addClass('rotate');
});
To remove the class once your animation has finished you have to listen for the animationend event like:
$('#myButton').click(function(){
// all the different event names are due to the fact that this isn't fully standardized yet
$('#myElementToAnimate').addClass('rotate').on('animationend webkitAnimationEnd oanimationend MSAnimationEnd', function(){
$(this).removeClass('rotate');
});
});
This should give you smoother results than using JavaScript based animation. See this demo fiddle

by simply applying the CSS properties and the desired values to jQuery
DEMO
$(' #box ').css({
transition: '2s linear',
transform: 'rotate(360deg)'
});
P.S: jQuery will handle all those -browser-specific prefixes for you.

Related

Jquery - Reverse animation on click (toggle or if/else)

I've tried a lot of different options and I'm sure most would work if I knew what I was doing.
I want to click on an image and make it larger and centered in the screen, then I want to click on the same image and return it back to normal.
In the two individual scripts below I have erased the reverse effect but I basically used functions that changed the css settings back to width:250, height:250, and marginLeft:9%. All I could get it to do successfully was enlarge an image but then it shrank automatically once it had fully enlarged. I need to make the function enlarge and then wait until I click the image again for it to shrink.
<script>
$('document').ready(function(){
$('.hello_mom').on('click', function(){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
});
});
</script>
<!--<script>//My idea with this second script was to set an initial variable that I would use to make the enlargement animation run (with an if statement) and the shrinking animation stop until the variable was changed at the end of the function. Once the variable changes the else statement would become true and run my reverse animation. However, it seems redundant when the animation still doesn't wait for another click to occur before it runs.
$a = 5;
$c = 10;
var b = $a;
if(b < $c) {
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 )};
</script>-->
you have 2 ways to do that ..
1- by using addClass and removeClass with transition
in css
.imageClicked{
width:350px;
height:350px;
zIndex:10;
marginLeft:28.4%;
transition : 0.5;
}
js
$('document').ready(function(){
$('.hello_mom').on('click', function(){
if($('.lbs_lease').hasClass('imageClicked')){
$('.lbs_lease').removeClass('imageClicked');
}else{
$('.lbs_lease').addClass('imageClicked');
}
});
});
2- by make another animate with default style and use boolean true or false
$('document').ready(function(){
var imgClicked = true;
$('.hello_mom').on('click', function(){
if(imgClicked == true){
$('.lbs_lease').animate({
width:"350px",
height:"350px",
zIndex:"10",
marginLeft:"28.4%"
}, 500 );
imgClicked = false;
}else{
$('.lbs_lease').animate({
//type your default style here
}, 500 );
imgClicked = true;
}
});
});
something like this:
var left = true;
$('.hello_mom').on('click', function () {
if (left) {
$(this).animate({
'marginLeft': "-=30px"
});
left = false;
} else {
$(this).animate({
'marginLeft': "+=30px"
});
left = true;
}
});
http://jsfiddle.net/e1cy8nLm/
You can do something like this: JSFiddle Demo
$('img').on('click', function(){
$(this).toggleClass( 'enlarge' );
});
CSS:
img {
// set the initial height and width here so we can animate these properties.
width:100px;
height:100px;
-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;
}
// toggle this class with jQuery to enlarge the img on click
.enlarge {
width:200px;
height:200px;
}
One of the methods will be using addClass and removeClass jquery functions keeping track of the current state of image.
The enlarged variable has the current state of the image and toggles it onclick with addition or removal of class.
Note the transition time is mentioned for both the classes, the added/removed as well as the original styling class to prevent abrupt transition while resizing to both states.
Here is a jsfiddle for that : JS FIDDLE DEMO
HTML Code :
<div>
<img class="hello_mom" src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg" />
</div>
CSS Code :
.hello_mom{
width:250px;
height:250px;
background : red;
-webkit-transition: all 0.5s; /* Safari */
transition: all 0.5s;
}
.hov_class{
width:350px;
height:350px;
z-index:10;
//margin-left:28.4%;
-webkit-transition: all 0.5s; /* Safari */
transition: all 0.5s;
}
JS Code :
var enlarged=0;
$('document').ready(function(){
$('.hello_mom').on('click', function(){
if(!enlarged){
$('.hello_mom').addClass("hov_class");
enlarged=1;
}
else{
$('.hello_mom').removeClass("hov_class");
enlarged=0;
}
});
});
Take a look at this
http://julian.com/research/velocity/
Velocity is javascript animation, made faster than CSS animation.
...and here you also have a reverse method

How to fadeIn element while making a transition?

Here is my problem:
http://jsfiddle.net/GDj7v/
$(document).ready(function () {
$("#field-type").change(function () {
$val = $(this).val();
if ($val == "checkbox") {
$("#check-boxes").addClass("shown");
} else {
$("#check-boxes").removeClass("shown");
}
})
});
Please click on the field type and choose checkbox. My nice transition to show hidden options is working. But I would like to HIDE #check-boxes element, so that it would not be so much white space between Field type and Description. I tried display:none on the #check-boxes element and then in Javascript fadeIn and I get very glitchy results.
Is it possible to do it?
Something like this?
$(document).ready(function() {
$('#check-boxes').hide();
$("#field-type").change(function() {
$val = $(this).val();
if($val == "checkbox") {
$('#check-boxes').show(0, function(){
$("#check-boxes").addClass("shown");
});
} else {
$("#check-boxes").removeClass("shown");
}
})
});
http://jsfiddle.net/GDj7v/3/
jQuery has built in methods of fading in/out. For example:
//replace $("#check-boxes").addClass("shown"); with
$("#check-boxes").show(400); //fade in 400 ms, essentially the same as jQuery's fadeIn()
//$("#check-boxes").removeClass("shown"); with
$("#check-boxes").hide(400); //fade out 400 ms, essentially the same as jQuery's fadeOut()
Show docs
Hide docs
Also, for custom animations you may want to look into jQuery's animate function. Take a look at the docs for detailed help.
You can easily change this by setting the margin-bottom property of your .form-group nodes to 0:
.form-group {
margin-bottom: 0;
}
If you want to use slideDown() and slideUp() with opacity you can do this way using animate()
if ($val == "checkbox") {
$("#check-boxes").css('opacity', 0).slideDown('slow').animate({ opacity: 1 },{duration: 'slow' });
} else {
$("#check-boxes").css('opacity', 1).slideUp('slow').animate({ opacity: 0 },{duration: 'slow' });
}
})
Demo Fiddle
Add this styles:
#check-boxes {
transition: all 1.2s ease-in-out;
transform: translateX(250px) rotateX(135deg);
opacity: 0;
display: none;
}
#check-boxes.shown {
transform: translateX(0px) rotateX(0deg);
opacity: 1;
display:block
}
I see what you mean, I was getting inconsistent results. As you'd expect, display isn't animatable which might be the issue when combining transitions with that.
I tried transitioning the height, but that made it look weird.
In the end I used a setTimeout to separate out changing the display property and making the transition:
http://jsfiddle.net/BYossarian/GDj7v/28/
HTML changes:
<div id="check-boxes" class="hidden">
CSS added:
.hidden {
display: none;
}
JS:
$(document).ready(function () {
$("#field-type").change(function () {
var $val = $(this).val(),
checkboxes = $("#check-boxes");
if ($val === "checkbox") {
checkboxes.removeClass('hidden');
setTimeout(function () {
checkboxes.addClass('shown');
}, 10);
} else {
checkboxes.removeClass('shown');
setTimeout(function () {
checkboxes.addClass('hidden');
}, 1210);
}
});
});
EDIT/ALTERNATE SOLUTION: Also, moving the transition property rule into the rules for #check-boxes.shown means the transition only happens in one direction, which clears up the issue I was having with height looking bad:
http://jsfiddle.net/BYossarian/GDj7v/30/
CSS:
#check-boxes {
-webkit-transform: translateX(250px) rotateX(135deg);
transform: translateX(250px) rotateX(135deg);
opacity: 0;
height: 0;
}
#check-boxes.shown {
transition: all 1.2s ease-in-out;
-webkit-transform: translateX(0px) rotateX(0deg);
transform: translateX(0px) rotateX(0deg);
opacity: 1;
height: auto;
}

jQuery css call back function

I'm trying to expand my searchbar using jQuery.
Also I want to hide the nav links.
I have some jQuery code like this. This code works fine when focus.
$(".searchBox input").focus(function(){
$("#navlinks").css('display','none');
$(this).css({'width':'200px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
});
$(".searchBox input").focus(function(){
$(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
$("#navlinks").css('display','block');
});
The second function also works fine except it display the content before animation complete.
So I want $("#navlinks").css('display','block'); to be exectuted only when animate complete.
Can anyone tell me how?
Thanks
.css() doesn't have a callback function, but .animate() does. Just set the time to 0 and use animate.
$(".searchBox input").on('focus',function(){
$(this).animate({width:100,mozTransition:'width 500ms ease-out',webkitTransition:'width 500ms ease-out',transition:'width 500ms ease-out'},0,function(){
$("#navlinks")
.delay(500)
.css({display:'block'});
});
});
Edit: included delay, which is required. (Thanks eicto)
Since you know how long takes your animations, why do not use setTimeout() after CSS change?
As far as I see your animation takes about 0.5 seconds. You could easily execute your "callback" seamlessly at end of your animation specifying the same amount of time in milliseconds.
$(".searchBox input").focus(function(){
$(this).css({'width':'100px','-moz-transition':'width 0.5s ease-out','-webkit-transition':'width 0.5s ease-out','transition':'width 0.5s ease-out'});
setTimeout( function() {
$("#navlinks").css('display','block');
}, 500);
});
I would recommend using .animate() like
$(".searchBox input").focus(function(){
$(this).animate({
'width': '100px'
}, 500, function() {
$("#navlinks").css('display', 'block');
});
});
This will work on all browsers, and the navlinks command will be insured to begin after the animation is complete. Note: the 500 is the number of milliseconds the animation will take to complete, so you can adjust accordingly.
Here is the .animate() documentation:
http://api.jquery.com/animate/
I came along here, but I used another solution:
$('.something').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",
function(event) {
// Do something when the transition ends
});
As you see, this is doing something, when the transition has ended.
This is described here:
http://blog.teamtreehouse.com/using-jquery-to-detect-when-css3-animations-and-transitions-end
Greetings,
Lars
Here is described
transitionend event, let's try that:
CSS:
#test {
width: 100px;
border: 1px solid black;
-webkit-transition: all 1s;
-moz-transition all 1s;
transition all 1s;
}
#test.wide {
width: 200px;
}
JS:
var test = $('#test');
test.bind('transitionend webkitTransitionEnd oTransitionEnd', function () {
$('body').append('<div>END!</div>');
})
$('button').click(function () {
test.toggleClass('wide');
});
DEMO

Add random to a css3 animation loop

Each time a css3 animation loops I'd like to change a variable in the style.
For example the following css drops a group of parachutes from the top to the bottom of the screen:
#-webkit-keyframes fall {
0% { top: -300px; opacity: 100; }
50% { opacity: 100; }
100% { top: 760px; opacity: 0; }
}
#parachute_wrap {
-webkit-animation-name: fall;
-webkit-animation-iteration-count: infinite;
-webkit-animation-duration: 70s;
-webkit-animation-timing-function: linear;
}
Ideally however, at the end of each loop I'd like to throw in a random X position.
The default style of the group is:
#parachute_wrap {
position: absolute;
top: -300px;
left: 50%;
margin-left: 140px;
}
So after 70 seconds, I would like to change the margin-left or left attribute anywhere between -200px and 200px.
I understand I could do something like this with jquery and everytime():
$('#parachute_wrap').everyTime ( 70000, function (){
$("#parachute_wrap").css({left: Math.floor(Math.random() * 51) + 5 + '%'},0);
});
But is there a way to tie the css loop to js to do this? i.e. is there a return call of any kind which js can listen to for perfect syncing with the animation? I fear that if I use JS on a 70s timer whats going to happen is the timing is going to not sync right, and half way through the css animation the js will do its timed loop and the parachutes are going to jump around the place half way through the animation.
How would you approach this?
CSS3 animations have an animationEnd event fired when the animation completes.
You can bind that event to your animated element thus triggering that left change at the end of each animation:
$('#parachute_wrap').on('webkitAnimationEnd mozAnimationEnd msAnimationEnd oAnimationEnd animationEnd', function(e) {
$(this).css({left: Math.floor(Math.random() * 51) + 5 + '%'},0);
});
This way, you know exactly when the animation ends and the left change is applied correctly.
There is also an animationiteration event fired at the start of every new animation iteration, i.e. every iteration except the first.
$('#parachute_wrap').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function(e) {
$(this).css({left: Math.floor(Math.random() * 51) + 5 + '%'},0);
});
http://www.w3.org/TR/css3-animations/#animationiteration

JQuery Fade On Hover Effect - help?

I'm trying to achieve a fade-on-hover effect with JQuery. Currently I have an element with a "hov" class attacked to it, without javascript the css will simply change it's color on :hover. With JQuery.
The idea is to clone the element as it's rolled over and place it directly infront, stripping it of the "hov" class so it's just static. Then I fade it out so it create the transition effect.
I'm having trouble though, after I strip the "hov" class from the clone, it KEEPS acting as though its still there. I can mouse over the clone even though it shouldn't be able to be targeted through hov. Any ideas / tips?
<a href="#" class="hov rounded-50 action-button">Fade Me Out< /a>
$(".hov").mouseover(function() {
// Clone the current element, remove the "hov" class so it won't trigger same behavior
// finally layer it infront of current element
var $overlay = $(this).clone(true).removeClass("hov").insertAfter($(this));
// Push it to the side just for testing purposes - fade it out
$overlay.css({left:'300px'}).fadeOut({duration:500, ease:'easeOutQuad'});
});
No need to clone the element, just fade the original element:
$('.hov').mouseenter(function() {
$(this).fadeOut();
});
// Optionally:
$('.hov').mouseleave(function() {
$(this).stop(true, true).show();
});
You can also use the hover function:
$('.hov').hover(function(){
$(this).fadeOut();
},
function(){
$(this).stop(true, true).show();
});
If you just want it to partially fade, you can animate the opacity property:
$('.hov').mouseenter(function() {
$(this).animate({'opacity': 0.5});
});
If you just want it to pulse, then return to normal opacity:
$('.hov').mouseenter(function() {
$this = $(this);
$this.animate({'opacity': 0.5}, {
'complete': function(){
$this.animate({'opacity': 1});
}
});
});
Finally, if your willing to forgo support of older browsers, you can do it all with css:
.hov {
-webkit-transition: opacity 0.3s ease-in;
-moz-transition: opacity 0.3s ease-in;
}
.hov:hover {
opacity: 0.5;
}

Categories

Resources