JQuery Fade On Hover Effect - help? - javascript

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;
}

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

what is ng-hide-add, ng-hide-active

I'm animating a div. It has the following definition:
<div ng-show="showTranslations" ng-swipe-right="showTranslationsBlock=false">...</div>
I have the following css defined:
div.ng-hide {
transition: 0.5s linear opacity;
opacity: 0;
}
div.ng-hide-add,
div.ng-hide-remove {
/* this needs to be here to make it visible during the animation
since the .ng-hide class is already on the element rendering
it as hidden. */
display:block!important;
}
This is taken from this tutorial. The animation works. But:
Why do I need these classes .ng-hide-add and .ng-hide-remove?
Why I don't see them added to div's classes?
Why there are also classes ng-hide-add-active and ng-hide-remove-active?
Why there is no transition when the div becomes visible although I've added the following css rule:
div.ng-hide-remove {
opacity: 1;
}
UPDATE
As I can see from the table provided by google's tutorial these classes are added to trigger animation frame (this performs a reflow). Is my understanding correct? Why is animation frame is mentioned there?
I tried to increase the transition period but it didn't add the classes. I didn't see the classes ng-hide-add-active and ng-hide-remove-active added either.
As I understand from the table these are the classes that trigger transition?
UPDATE1
I've explored the Angular's source code and found the following for the ng-hide directive:
var ngHideDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
$animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
});
};
}];
As I understand the ng-hide class is added through animation service. But what happens if I don't use animations and $animate service is not available? How Angular is going to handle this situation given the code above and how it is going to add ng-hide class? Or is this $animate.addClass() simply adds a callback to addClass event?
Put your CSS transition on ng-hide-remove, ng-hide-remove-active:
div.ng-hide-remove {
transition: 0.5s linear opacity;
opacity: 0;
}
div.ng-hide-remove-active {
opacity: 1;
}
Similarly, for ng-hide-add and ng-hide-add-active:
div.ng-hide-add {
transition: 0.5s linear opacity;
opacity: 1;
}
div.ng-hide-add-active {
opacity: 0;
}

Fade in / fade out background color of an HTML element with Javascript (or jQuery)

I have a table whose row needs to be highlighted & then cleared. I'm using contextual classes to color the table rows (not a necessary requirement). The javascript part is given below. How can I animate i.e. fadeIn / fadeOut the coloring of rows using javascript / jQuery / Bootstrap. The code below instantly adds & removes the color.
$('tr').eq(1).addClass('success');
setTimeout(function(){
$('tr').eq(1).removeClass('success');
},2000);
http://jsfiddle.net/5NB3s/
P.S. Trying to avoid the jQuery UI route here How do you fade in/out a background color using jquery?
Here's what I cooked up. It works nicely without the need of any UI library. Even jQuery can be eliminated if needed.
//Color row background in HSL space (easier to manipulate fading)
$('tr').eq(1).css('backgroundColor','hsl(0,100%,50%');
var d = 1000;
for(var i=50; i<=100; i=i+0.1){ //i represents the lightness
d += 10;
(function(ii,dd){
setTimeout(function(){
$('tr').eq(1).css('backgroundColor','hsl(0,100%,'+ii+'%)');
}, dd);
})(i,d);
}
Demo : http://jsfiddle.net/5NB3s/2/
SetTimeout increases the lightness from 50% to 100%, essentially making the background white (you can choose any value depending on your color).
SetTimeout is wrapped in an anonymous function for it to work properly in a loop ( reason )
One way could be :
JS :
$('tr').eq(1).hide().addClass('success').fadeIn('slow');
setTimeout(function(){
$('tr').eq(1).fadeOut('slow',function(){ $(this).removeClass('success').show();});
},2000);
Bootply : http://www.bootply.com/123956
UPDATE
Second way, much better, but... I'll explain :
Bootply : http://www.bootply.com/123956 [still the same url don't worry]
JS :
$('tr').eq(1).animate({
backgroundColor: "#dff0d8"
}, 2000 );
setTimeout(function(){
$('tr').eq(1).animate({
backgroundColor: "#ffffff"
}, 2000 );
},2000);
You have to use jQueryUI animate and the result it's visually good...
I had the same problem and couldn't find an easy way to do it other than programming. Another way to achieve fadding BG colors is using CSS properties for each row when hovering them.
#RowID{
background-color: #ececec;
background-color: rgba(236, 236, 236, 0.901961);
-moz-transition: background-color 1s cubic-bezier(1,1,1,1);
-moz-transition-delay: 0.5s;
-ms-transition: background-color 1s cubic-bezier(1,1,1,1);
-ms-transition-delay: 0.5s;
-o-transition: background-color 1s cubic-bezier(1,1,1,1);
-o-transition-delay: 0.5s;
-webkit-transition: background-color 1s cubic-bezier(1,1,1,1);
-webkit-transition-delay: 0.5s;
transition: background-color 1s cubic-bezier(1,1,1,1);
transition-delay: 0s;
}
#RowID:hover {
background-color: rgb(206, 128, 128);
}
In addition you can always set the delay you want for the BG to change setting the transition-delay property.
JSFiddle
Similar to user's answer above, except to handle the fade, I change the opaque value to fade in and out. I also use the id tag to target different table cells, so we use different colors. First you need to tag the cell with an id attribute:
<td id="cellToShade">.01</td>
Then put the javascript in line below to set the timeouts and change the opaque value:
<script>
var d = 500;
var opaqueness=.05;
for(var i=0; i<=600; i=i+1){
d += 10;
opaqueness += .0001;
(function(i,d, opaqueness){
setTimeout(function(){
document.getElementById("cellToShade").style.background = "rgba(255, 0, 0, "+ opaqueness +")";
}, d);
})(i,d, opaqueness);
}
</script>
You might want to play around with the opaqueness variable, i, and d to get the effect timing you want.
jQuery already has a fadeOut() option. Why not just use that and a div positioned behind the element-to-highlight? All you need is a little CSS/JavaScript magic. It's easy, and you get the nice, smooth fadeOut() coded up by jQuery developers...
JSBin Demo --
function highlightElement(element) {
const background = $('<div></div>');
$(background).css({
'position':'relative',
'top':'-' + $(element).height() + 'px',
'background-color':'yellow',
'z-index':'-10',
'height':$(element).height() + 'px',
'width':$(element).width() + 'px',
'margin-bottom':'-' + $(element).height() + 'px',
'padding':'0px',
'float':'left',
});
$(background).appendTo(element);
$(background).fadeOut(5000);
return true;
}
To add some explanation:
background CSS uses a combination of a negative margin-bottom (calculated from element size) and a negative top, as well, to position it correctly. width, of course, is set, but that just affects width and not overall placement. z-index forces the dummy element we're making to be underneath.
fadeOut(5000) fades out the dummy background element we just created.
The 105 of the rgb(255,255,105) is how yellow to start. The 100 in the setInterval call is how fast the yellow fades to white.
<div id="x" style="background-color:rgb(255,255,105)">hello world</div>
<script type="text/javascript">
var unBlue=105;
var gEvent=setInterval("toWhite();", 100);
function toWhite(){
if(unBlue<255) document.getElementById("x").style.backgroundColor="rgb(255,255,"+unBlue+")";
else clearInterval(gEvent)
unBlue+=10;
}
</script>

How to use css method of rotation in jquery

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.

Fading visibility of element using jQuery

I'm having some trouble with finding the visibility param for JQuery.
Basically... the code below does nothing.
$('ul.load_details').animate({
visibility: "visible"
},1000);
There's nothing wrong with the animate code (I replaced visibility with fontSize and it was fine. I just can't seem to find the correct param name equivalent for "visibility" in css.
You could set the opacity to 0.0 (i.e. "invisible") and visibility to visible (to make the opacity relevant), then animate the opacity from 0.0 to 1.0 (to fade it in):
$('ul.load_details').css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1.0});
Because you set the opacity to 0.0, it's invisible despite being set to "visible". The opacity animation should give you the fade-in you're looking for.
Or, of course, you could use the .show() or .fadeTo() animations.
EDIT: Volomike is correct. CSS of course specifies that opacity takes a value between 0.0 and 1.0, not between 0 and 100. Fixed.
Maybe you are just looking to show or hide an element:
$('ul.load_details').show();
$('ul.load_details').hide();
Or do you want to show/hide element using animation (this doesn't make sense of course as it will not fade):
$('ul.load_details').animate({opacity:"show"});
$('ul.load_details').animate({opacity:"hide"});
Or do you want to really fade-in the element like this:
$('ul.load_details').animate({opacity:1});
$('ul.load_details').animate({opacity:0});
Maybe a nice tutorial will help you get up to speed with jQuery:
http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/
You can't animate visibility. Either something is visible, or it's not (event 1% opaque items are 'visible'). It's much like half-existing - doesn't make sense. You're likely better off animating the opacity (via .fadeTo() etc).
This might help:
$(".pane .delete").click(function(){
$(this).parents(".pane").animate({ opacity: 'hide' }, "slow");
});
This is what worked for me (based on #Alan's answer)
var foo = $('ul.load_details'); // or whatever
var duration = "slow"; // or whatever
if (foo.css('visibility') == 'visible') {
foo.css({ opacity: 1 }).animate({ opacity: 0 }, duration, function () {
foo.css({ visibility: "hidden" });
});
} else {
foo.css({ opacity: 0 }).animate({ opacity: 1 }, duration).css({ visibility: "visible" });
}
When the foo element is visible, then slowly change the opacity to zero (via animate) and then wait until that's done before setting foo's visibility to be hidden. Otherwise, if set to hidden during the animate process then the fading out effect will not happen since it's hidden immediately.
Alternatively, you can use the simpler, cleaner fadeTo():
var foo = $('ul.load_details'); // or whatever
var duration = "slow"; // or whatever
if (foo.css('visibility') == 'visible') {
foo.fadeTo(duration, 0, function () {
foo.css({ visibility: "hidden" });
});
} else {
foo.fadeTo(duration, 1).css({ visibility: "visible" });
}

Categories

Resources