Animating a div when hovered - javascript

I have a navigation bar that sticks out a little bit from the right edge of the screen. I want it so when you hover on the div, it slides left 550px out of the right side of the browser. I'm using jquery's animate function and I got it to animate properly when hovered, but I can't get it to slide back to the right when you stop hovering on it.
I'm very new to javascript/jquery and I feel like I'm missing something simple...
$(document).ready(function(){
$("#nav").hover(function() {
$(this).animate({
right: "0px",
}, 800 );
(function() {
$(this).animate({
right: "-550px",
}, 800 );
});
});
});
And here's #nav's css:
#nav {
position: absolute;
right: -550px;
min-width: 300px;
top: 10px;
height: 50px;
background-color: #B30431;
}

The code has some syntax errors. The code should be :
$(document).ready(function(){
$("#nav").hover(
function() {
$(this).animate({ right: "0px" }, 800 );
},
function() {
$(this).animate({ right: "-550px" }, 800);
}
});
});
Good Luck !!

You have made your hover function complicated, you have wrapped the function with () and your function is not executed.
$(document).ready(function() {
$("#nav").hover(function() {
$(this).animate({ right: "0px" }, 800);
}, function() {
$(this).animate({ right: "-550px" }, 800);
});
});​

One option, which we use a lot for our animation, is to make a css class that contains that animation, and then ise the .addClass() method to trigger the animation. Its fast, and its browser compatible. You could also use pure css for this.

You could try this...Demo
$(document).ready(function(){
$("#nav").mouseover(function(){
$(this).delay(200).animate({right: "0px"}, 800 );
// Added a 200ms delay to prevent quick accidental mouse overs triggering animation.
});
$("#nav").mouseout(function(){
$(this).clearQueue();
// Gives the user the ability to cancel the animation by moving the mouse away
$(this).animate({right: "-550px"}, 800 );
});
});

Related

Javascript button appear animation

I have the back to top button that appears when you reach a point on the page, which is working fine, however, when it appears the text is on two lines until the box has finished the animation to appear. So, is there anyway to prevent this? What I mean by the animation is: btt.show('slow');
Code:
$(document).ready(function () {
var btt = $('.back-to-top');
btt.on('click' , function(e) {
$('html, body').animate({
scrollTop: 0
}, 500);
btt.hide('slow');
e.preventDefault();
});
$(window).on('scroll', function () {
var self = $(this),
height = self.height(),
top = self.scrollTop();
if (top > 500) {
btt.show('slow');
} else {
btt.hide('slow');
}
});
});
Example: http://codepen.io/Riggster/pen/WvNvQm
The problem is caused by animating the width of a box, I think it might be better to animate the position of it instead, but - even better - lets use CSS animations!
$(window).on('scroll', function () {
if ($(window).scrollTop() >= 500) {
$(".button").addClass('show');
} else {
$(".button").removeClass('show');
}
});
#wrapper {
width: 100%;
height: 2000px;
}
.button {
position: fixed;
bottom: 50px;
right: -100px;
/* You might still need prefixes here. Use as preferred. */
transition: right 500ms;
}
.button.show {
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div id="wrapper">
<div class="button">Here's my button!</div>
</div>
I've defined your button as hidden by default, by giving it a position of right: -100px. When we hit the correct scroll position, we add the class show and that triggers the animation performed by CSS and not javascript, as we have the transition property for the property right defined - that way the browser does the heavy lifting.
Toggling show/hide alters your elements width. You either have to put it in a container with display: inline
Or more ideally you might want to change show/hide to jQuery fadeIn() / fadeOut() which is more appropriate for "Back to Top" indicators.
Here is your codepen example modified with inline container:
http://codepen.io/anon/pen/MwWweY

Jquery Animation Menu

I put together a jQuery animation for a menu background. The menu has a dropdown and when you hover over the menu the animation kicks in, but the dropdown starts to act all wonky. Pretty new to jquery so not sure why this is doing that.
I added a div (menu-bg) with absolute position to change height on hover inside the menu.
Here is my javascript controlling the animation:
$('.navbar-nav >li > a').hover(
function() {
$(this).stop().next().animate({
height: "60px"
}, {
easing: "swing",
queue: true,
duration: 400
});
},
function() {
$(this).stop().next().animate({
height: "0px"
}, {
easing: "swing",
queue: true,
duration: 200
});
});
Here is a link to the site to view the actual issue, you will notice it when you hover over home.
http://bratworks.com/static
I found the following changes in your code got the job done:
Inside of init.js around line 15 remove the 200 millisecond delay from the dropdown menu fadeOut().
$(this).find('.dropdown-menu').stop(true, true).delay(0).fadeOut();
I re-wrote your hover function to target the li's instead of the a, it looked like there was some kind of conflict there:
$('.navbar-nav > li').on({
mouseenter: function() {;
$(this).find('.menu-bg').animate({ height: "60px" });
},
mouseleave: function() {
$(this).find('.menu-bg').animate({ height: "0px" });
}
});
And finally, I overwrote the CSS that was creating that 5px margin gap on the .dropdown-menu:
.dropdown-menu {
margin-top:0px!important;
}
There you go! Please let me know if you'd like me to expand on anything?

jQuery animating issues?

So far, I have a pretty decent code to animate a center box. For some reason, when I preview this on different browsers and computer (Mac and PC) I get different results. One may show a faster animation speed, while the other is perfect. I have also noticed that when the box is being animated from left to right, there is a stutter, and the animation jerks. I can't really explain it more than that. My code is below:
$(document).ready(function(){
isAnimating = false;
$('.wrapper').on('click', '.arrow-left', function() {
if(isAnimating) return;
isAnimating = true;
var $current = $(this).parents('.signupBox');
var $next = $(this).parents('.signupBox').next();
$current.stop(true,true).animate({
left: "200%"
}, 500, 'linear', function() {
$current.css({
left: "-200%"
}).appendTo('.wrapper'); // move to end of stack
$next.css({
left: "-200%"
}).stop(true,true).animate({
left: "0%"
}, 500, 'linear', function() {
isAnimating = false;
});
});
}).on('click', '.arrow-right', function() {
if(isAnimating) return;
isAnimating = true;
var $current = $(this).parents('.signupBox');
var $next = $(this).parents('.signupBox').siblings().last();
$current.stop(true,true).animate({
left: "-200%"
}, 500, 'linear', function() {
$current.css({
left: "200%"
});
$next.prependTo('.wrapper') // move to front of stack
.css({
left: "200%"
}).stop(true,true).animate({
left: "0%"
}, 500, 'linear', function() {
isAnimating = false;
});
});
});
});
Some CSS:
.signupBox:first-child {
display: block;
}
.signupBox {
display: none;
}
.wrapper
{
overflow: hidden;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
position: absolute;
}
Here's a JSFiddle showing what happens, hopefully you can see what's the issue from there.
Then animation from right to left (click on the < symbol and you will see a slign change in speed.
Different browsers could have different results when using JS and css transitions, it actually depends on your machine speed, browser speed as well. It could depend on how many opened tabs you have in each browser, browsers plugins could freeze animations as well. Other JS events as well.
I have tested your code in Chrome, FF (wasn't able to check it in IE11, it seems there are JS errors on jsfiddler using jQuery). Didn't mentioned something strange.
I could recommend to use Greenshock JS animating library. http://www.greensock.com/get-started-js/
They say it's x20 times faster jQuery animate. But i think actually may be in 2,3 )
That libruary is based on Flash library that was used by Action Script coders to create beauty animations in Flash.

Possible to toggle/animate between two sizes using jQuery?

Basically I have a small div that is initially styled to 60x60. I have created click event that animates the expansion of the div:
$("#myDiv").click(function () {
$(this).animate(
{
width: "350px",
height: "300px"
}, 500);
}
I would like to reverse this animation if someone clicks the div again. Is there anyway to toggle between the original size and the expanded size (still using the animate function) with each click?
I found the toggleClass function but I don't think this will work with animiate.
You can see a basic fiddle here: http://jsfiddle.net/NS9Qp/
$("#myDiv").toggle(function() {
$(this).stop().animate({
width: "350px",
height: "300px"
}, 500);
}, function() {
$(this).stop().animate({
width: "60px",
height: "60px"
}, 500);
});
Example.
The jQuery toggle() function allows you to define two or more functions to cycle through on each mouse click. In this case, the first one (triggered on the first click) expands the div and the second one (triggered on the second click) resets it. On the third click, it starts back at the first one, and so on.
More about toggle() here.
just to be different :
var size=[];
$("#cornerBox").click(function(){
$(this).width() >= 350 ? size=[60, 60] : size=[350, 300];
$(this).stop().animate({ width: size[0], height: size[1] },500);
});
Fiddle: http://jsfiddle.net/NS9Qp/1/
I ended up using jQuery UI's animated toggleClass effect: http://jqueryui.com/demos/toggleClass/
super simple code:
$('h2').click(function() {
$(this).next().toggleClass("hidden", 1000);
});
Do not hardcode css styles (in my example I used inline css for myDiv element, put this in css files).
<div id="myDiv" style="background:red; width: 60px; height: 60px;"></div>
<script type="text/javascript">
var div = $('#myDiv');
div
.attr('defWidth', div.width())
.attr('defHeight', div.height())
.toggle(function() {
$(this).stop().animate({width: "350px", height: "300px"}, 500);
}, function() {
$(this).stop().animate({width: $(this).attr('defWidth'), height: $(this).attr('defHeight')}, 500);
}
);
</script>
What I do for cases like this, is store a transformation array.
var transforms = { 'height0': 60, 'width0': 60, 'height1': 300, 'width1': 350};
Then, store a toggle between 0 or 1, and use the corresponding values for the animation.
EDIT: combine this with the previous example of toggle, and you've got yourself a solid working solution!

jQuery slideUp to show the element and not hide

jQuery's slideUp effect hides the element by sliding it up, while slideDown shows the element. I want to show my div using slideUp. can anyone guide me ? thanks
$("div").click(function () {
$(this).hide("slide", { direction: "down" }, 1000);
});
http://docs.jquery.com/UI/Effects/Slide
It's a little more complex than just saying slideUpShow() or something, but you can still do it. This is a pretty simple example, so you might find some edge-cases that need adressing.
$("#show-animate-up").on("click", function () {
var div = $("div:not(:visible)");
var height = div.css({
display: "block"
}).height();
div.css({
overflow: "hidden",
marginTop: height,
height: 0
}).animate({
marginTop: 0,
height: height
}, 500, function () {
$(this).css({
display: "",
overflow: "",
height: "",
marginTop: ""
});
});
});
Here's a fiddle showing the slideUp/slideDown methods, the same effects using animate, and a modified version using animate that goes in reverse: http://jsfiddle.net/sd7zsyhe/1/
Since animate is a built-in jQuery function, you don't need to include jQuery UI.
To get the opposite of slideUp and slideDown. Add these two functions to jQuery.
$.fn.riseUp = function() { $(this).show("slide", { direction: "down" }, 1000); }
$.fn.riseDown = function() { $(this).hide("slide", { direction: "down" }, 1000); }
I found a tricky way...
you can set div with css style bottom:0px,
add call
$("#div).slideDown();
will show with the slideUp-to-show effect you want.
Jquery toggle
This toggle effect is only for up and down. Jquery UI is for every other direction
For those who don´t use the Jquery UI but want to add the function to Jquery Library:
jQuery.fn.slideUpShow = function (time,callback) {
if (!time)
time = 200;
var o = $(this[0]) // It's your element
if (o.is(':hidden'))
{
var height = o.css({
display: "block"
}).height();
o.css({
overflow: "hidden",
marginTop: height,
height: 0
}).animate({
marginTop: 0,
height: height
}, time, function () {
$(this).css({
display: "",
overflow: "",
height: "",
marginTop: ""
});
if (callback)
callback();
});
}
return this; // This is needed so others can keep chaining off of this
};
jQuery.fn.slideDownHide = function (time,callback) {
if (!time)
time = 200;
var o = $(this[0]) // It's your element
if (o.is(':visible')) {
var height = o.height();
o.css({
overflow: "hidden",
marginTop: 0,
height: height
}).animate({
marginTop: height,
height: 0
}, time, function () {
$(this).css({
display: "none",
overflow: "",
height: "",
marginTop: ""
});
if (callback)
callback();
});
}
return this;
}
Credits: #redbmk answer
Despite the name, slideDown can actually slide your element both ways. Use absolute position if it is required to animate inside the parent element:
#slideup {
position:fixed;
bottom:0;
background:#0243c9;
color:#fafefa;
width:100%;
display:none;
padding: 20px;
}
#littleslideup {
position:absolute;
bottom:0;
background:#000;
color:#fff;
display:none;
padding:10px;
z-index:100;
}
#slidedown {
position:fixed;
top:0;
background:#c94333;
color:#fafefa;
width:100%;
display:none;
padding: 20px;
}
button {
display:inline-block;
font-size:16px;
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="position:relative">This amounts to 70% of the total timber stand area of the region (not including the dwarf pine and shrubby alder) and is more than the total area of all other stone birch forests growing in the Magadan, Khabarovsk, Primorye and Sakhalin regions and other areas of its distribution.
<div id="littleslideup">Absolute-positioned element</div>
</div>
<span style="color:red">Click >> </span>
<button onclick="jQuery('#slideup').slideDown(1500);" >"Slideup"</button>
<button onclick="jQuery('#slidedown').slideDown(1500);" >"Slidedown"</button>
<button onclick="jQuery('#littleslideup').slideDown(1500);">"Slideup" inside element</button>
<div>Finally, closing the subject of volcanic activity, it must be said that the stone birch stands by its functional reaction quite adequately in order to re ect the character and intensity of the physical, chemical and thermic processes, stipulated by volcanism as well as the in uence upon biota and ecosystems.</div>
<div id="slideup">Could be a bottom cookie warning bar</div>
<div id="slidedown">Could be a top cookie warning bar</div>
I've got some downvotes so I checked my answer and indeed I didn't answered correctly the OP question, sorry. So I'm gonna try to fix that.
First, the slideUp() method in JQuery is intended to hide the element rather than reveal it. It is basically the opposite of slideDown() which shows your element by sliding it down.
By knowing that I think we agree that there is no magic function right there to do a slide up effect to show an element (in JQuery).
So we need to do a little bit of work to get what we need: slid up reveal effect. I found out some solutions and here is one I think simple to implement:
https://coderwall.com/p/9dsvia/jquery-slideup-to-reveal
The solution above works with the hover event, for the click event try this modified code:
http://jsfiddle.net/D7uT9/250/
The answer given by #redbmk is also a working solution.
Sorry for my misunderstanding the first time.
OLD ANSWER
It's an old post, but if someone is looking for a solution here is my recommandation.
We can, now, use slideToggle() to achieve this effect (without the need of jQuery UI).
$(".btn").click(function () {
$("div").slideToggle();
});
Documentation: http://api.jquery.com/slidetoggle/
Having encountered this with a student looking to "slide up always hide" an error container, I advised he simply use CSS transitions:
.slide-up {
transition: 1s ease-out;
transform: scale(1);
}
.slide-up[aria-hidden="true"] {
transform: scale(0);
height: 0;
}
jQuery(document).ready(function($) {
const $submitButton = $(".btn");
const $someDivs = $("div");
const $animatedSlidingTargets = $(".slide-up");
$someDivs.on("click", function() {
$animatedSlidingTargets.attr("aria-hidden", true);
});
});
For #Jason's answer, whether slide-up to show and slide-down to hide, you still need to use the { direction: "down" } option in jQuery:
$(".btnAbout").on("click", function () {
// Slide-up to show
$("#divFooter").show("slide", { direction: "down" }, 1000);
});
$("#btnCloseFooter").on("click", function () {
// Slide-down to hide
$("#divFooter").hide("slide", { direction: "down" }, 1000);
});
But this requires jquery-ui, or else you'll hit the TypeError: something.easing[this.easing] is not a function error:
<script defer src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>

Categories

Resources