i've to animate an image form right side. when page scrolls down its invisible and when page reaches there image floats from right now i can detect the position of the scroll like this
jQuery(document).ready(function($){
var target = $(".myimages").offset().top;
var interval = setInterval(function() {
if ($(window).scrollTop() >= target) {
alert("image found ");
//here float the image
}
}, 250);
});
now i want to do is float the image from right corner to its width. i only know its can use animation like this
$('.myimages').animate({css properties here})
but don't know how to use it so please help
Here is jQuery API for animate function: http://api.jquery.com/animate/
and some example how to use it:
$( ".myimages" ).animate({
right: "100px",
width: "200px"
}, 1000);
Post your working code on jsfiddle, so we can help you better.
I think it is better to use.
by default use css3 transform to place it to the right
$(document).ready(function(){
initAnimation();
});
function initAnimation() {
var win = $(window);
var targetImage = $('.myimages');
var animate = function() {
if ($(window).scrollTop() >= targetImage.offset().top) {
targetImage.addClass('active');
}
else {
targetImage.removeClass('active');
}
};
win.on('load scroll', animate);
}
.myimages {
transform: translate(100%, 0);
transition: transform 0.5s ease-in-out;
}
.myimages.active {
transform: translate(0, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Situation
.rightnav.front is clicked for DIV1.
DIV1 moves to the right, and opacity is lowered
DIV1 moves back left, and at completion opacity is 0
DIV1 gets class .hidden and .offset to hide it and to move it off screen, so it's not clickable anymore..
The next DIV (DIV with id 2 for test-purposes) has it's hidden and offset classes removed, and is the target for the next click-event.
Problem
The DIV moves right, but doesn't move left (back again) before it's hidden. See Codepen at the bottom for a try-out.
I'm only posting the JavaScript code here.. CSS and HTML you'll find in the codepen.
Here is the jQuery code
$(document.body).on('click','.rightnav.front', function () {
var x = $(this).parent().parent();
x.addClass('moveright')
.one('transitionend', function() {
x.removeClass('moveright')
})
.one('transitionend', function(){
x.addClass('moveleft');
})
.one('transitionend', function() {
x.addClass('hidden').addClass('offset');
$('.rightnav.front').removeClass('front');
var nextId = Number(x.attr('id')) + 1;
var nextWidget = $('#' + nextId);
nextWidget.removeClass('hidden');
nextWidget.children().find('.rightnav').addClass('front');
})
});
CodePen
Here is the CodePen.IO link for a live test: http://codepen.io/nygter/pen/QbpegM
Take a look at this solution, maybe (sure) it's not ideal, but should work as expected. As I mentioned in comment I've moved animation from jQuery to #keyframes.
Magic cames from:
.widget.moveright{
left:450px;
margin-left:-100px;
opacity:0.5;
}
and
x.addClass('moveright')
.one('transitionend', function() {
x.removeClass('moveright')
})
.one('transitionend', function(){
x.addClass('moveleft');
}) //...
Transformed into:
#keyframes moveright{
50% {
left:450px;
margin-left:-100px;
opacity:0.5;
}
100% {
opacity: 0;
}
}
.widget.moveright{
animation: moveright 1s ease;
-webkit-animation: moveright 1s ease;
}
and
x.addClass('moveright')
.one('animationend', function() {
$(this)
.removeClass('moveright')
.addClass('hidden offset');
//...
See it in action at Codepen.
To understand CSS animations take a look.
I'm using bootstrap, and I'd like to add animation to a dropdown. I want to add an animation to it, slide down and back up when leaving it.
How could I do this?
Things I tried:
Changing the Js drop down file like this:
How can I make Bootstrap's navigation dropdown slide smoothly up and down?
If you update to Bootstrap 3 (BS3), they've exposed a lot of Javascript events that are nice to tie your desired functionality into. In BS3, this code will give all of your dropdown menus the animation effect you are looking for:
// Add slideDown animation to Bootstrap dropdown when expanding.
$('.dropdown').on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// Add slideUp animation to Bootstrap dropdown when collapsing.
$('.dropdown').on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
You can read about BS3 events here and specifically about the dropdown events here.
Also it's possible to avoid using JavaScript for drop-down effect, and use CSS3 transition, by adding this small piece of code to your style:
.dropdown .dropdown-menu {
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
max-height: 0;
display: block;
overflow: hidden;
opacity: 0;
}
.dropdown.open .dropdown-menu { /* For Bootstrap 4, use .dropdown.show instead of .dropdown.open */
max-height: 300px;
opacity: 1;
}
The only problem with this way is that you should manually specify max-height. If you set a very big value, your animation will be very quick.
It works like a charm if you know the approximate height of your dropdowns, otherwise you still can use javascript to set a precise max-height value.
Here is small example: DEMO
! There is small bug with padding in this solution, check Jacob Stamm's comment with solution.
I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});
I don't know if I can bump this thread, but I figured out a quick fix for the visual bug that happens when the open class is removed too fast. Basically, all there is to it is to add an OnComplete function inside the slideUp event and reset all active classes and attributes. Goes something like this:
Here is the result: Bootply example
Javascript/Jquery:
$(function(){
// ADD SLIDEDOWN ANIMATION TO DROPDOWN //
$('.dropdown').on('show.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
});
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
e.preventDefault();
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(400, function(){
//On Complete, we reset all active dropdown classes and attributes
//This fixes the visual bug associated with the open class being removed too fast
$('.dropdown').removeClass('show');
$('.dropdown-menu').removeClass('show');
$('.dropdown').find('.dropdown-toggle').attr('aria-expanded','false');
});
});
});
here is my solution for slide & fade effect:
// Add slideup & fadein animation to dropdown
$('.dropdown').on('show.bs.dropdown', function(e){
var $dropdown = $(this).find('.dropdown-menu');
var orig_margin_top = parseInt($dropdown.css('margin-top'));
$dropdown.css({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}).animate({'margin-top': orig_margin_top + 'px', opacity: 1}, 300, function(){
$(this).css({'margin-top':''});
});
});
// Add slidedown & fadeout animation to dropdown
$('.dropdown').on('hide.bs.dropdown', function(e){
var $dropdown = $(this).find('.dropdown-menu');
var orig_margin_top = parseInt($dropdown.css('margin-top'));
$dropdown.css({'margin-top': orig_margin_top + 'px', opacity: 1, display: 'block'}).animate({'margin-top': (orig_margin_top + 10) + 'px', opacity: 0}, 300, function(){
$(this).css({'margin-top':'', display:''});
});
});
Update 2018 Bootstrap 4
In Boostrap 4, the .open class has been replaced with .show. I wanted to implement this using only CSS transistions without the need for extra JS or jQuery...
.show > .dropdown-menu {
max-height: 900px;
visibility: visible;
}
.dropdown-menu {
display: block;
max-height: 0;
visibility: hidden;
transition: all 0.5s ease-in-out;
overflow: hidden;
}
Demo: https://www.codeply.com/go/3i8LzYVfMF
Note: max-height can be set to any large value that's enough to accommodate the dropdown content.
On click it can be done using below code
$('.dropdown-toggle').click(function() {
$(this).next('.dropdown-menu').slideToggle(500);
});
I am using the code above but I have changed the delay effect by slideToggle.
It slides the dropdown on hover with animation.
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400);
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideToggle(400)
});
For Bootstrap 5 a simple and beautiful slide in animation can be done with a simple keframe animation.
#keyframes slideIn {
0% {
transform: translateY(1rem);
opacity: 0;
}
100% {
transform: translateY(0rem);
opacity: 1;
}
}
.slideIn {
-webkit-animation-name: slideIn;
animation-name: slideIn;
animation-duration: 0.4s;
animation-fill-mode: both;
}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle m-2" href="/" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropdown
</a>
<ul class="dropdown-menu slideIn rounded-2 p-3" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="/">Action</a></li>
<li><a class="dropdown-item" href="/">Another action</a></li>
<li><hr class="dropdown-divider"/></li>
<li><a class="dropdown-item" href="/">Something else here</a></li>
</ul>
</li>
Expanded answer, was my first answer so excuse if there wasn’t enough detail before.
For Bootstrap 3.x I personally prefer CSS animations and I've been using animate.css & along with the Bootstrap Dropdown Javascript Hooks. Although it might not have the exactly effect you're after it's a pretty flexible approach.
Step 1: Add animate.css to your page with the head tags:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css">
Step 2: Use the standard Bootstrap HTML on the trigger:
<div class="dropdown">
<button type="button" data-toggle="dropdown">Dropdown trigger</button>
<ul class="dropdown-menu">
...
</ul>
</div>
Step 3: Then add 2 custom data attributes to the dropdrop-menu element; data-dropdown-in for the in animation and data-dropdown-out for the out animation. These can be any animate.css effects like fadeIn or fadeOut
<ul class="dropdown-menu" data-dropdown-in="fadeIn" data-dropdown-out="fadeOut">
......
</ul>
Step 4: Next add the following Javascript to read the data-dropdown-in/out data attributes and react to the Bootstrap Javascript API hooks/events (http://getbootstrap.com/javascript/#dropdowns-events):
var dropdownSelectors = $('.dropdown, .dropup');
// Custom function to read dropdown data
// =========================
function dropdownEffectData(target) {
// #todo - page level global?
var effectInDefault = null,
effectOutDefault = null;
var dropdown = $(target),
dropdownMenu = $('.dropdown-menu', target);
var parentUl = dropdown.parents('ul.nav');
// If parent is ul.nav allow global effect settings
if (parentUl.size() > 0) {
effectInDefault = parentUl.data('dropdown-in') || null;
effectOutDefault = parentUl.data('dropdown-out') || null;
}
return {
target: target,
dropdown: dropdown,
dropdownMenu: dropdownMenu,
effectIn: dropdownMenu.data('dropdown-in') || effectInDefault,
effectOut: dropdownMenu.data('dropdown-out') || effectOutDefault,
};
}
// Custom function to start effect (in or out)
// =========================
function dropdownEffectStart(data, effectToStart) {
if (effectToStart) {
data.dropdown.addClass('dropdown-animating');
data.dropdownMenu.addClass('animated');
data.dropdownMenu.addClass(effectToStart);
}
}
// Custom function to read when animation is over
// =========================
function dropdownEffectEnd(data, callbackFunc) {
var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
data.dropdown.one(animationEnd, function() {
data.dropdown.removeClass('dropdown-animating');
data.dropdownMenu.removeClass('animated');
data.dropdownMenu.removeClass(data.effectIn);
data.dropdownMenu.removeClass(data.effectOut);
// Custom callback option, used to remove open class in out effect
if(typeof callbackFunc == 'function'){
callbackFunc();
}
});
}
// Bootstrap API hooks
// =========================
dropdownSelectors.on({
"show.bs.dropdown": function () {
// On show, start in effect
var dropdown = dropdownEffectData(this);
dropdownEffectStart(dropdown, dropdown.effectIn);
},
"shown.bs.dropdown": function () {
// On shown, remove in effect once complete
var dropdown = dropdownEffectData(this);
if (dropdown.effectIn && dropdown.effectOut) {
dropdownEffectEnd(dropdown, function() {});
}
},
"hide.bs.dropdown": function(e) {
// On hide, start out effect
var dropdown = dropdownEffectData(this);
if (dropdown.effectOut) {
e.preventDefault();
dropdownEffectStart(dropdown, dropdown.effectOut);
dropdownEffectEnd(dropdown, function() {
dropdown.dropdown.removeClass('open');
});
}
},
});
Step 5 (optional): If you want to speed up or alter the animation you can do so with CSS like the following:
.dropdown-menu.animated {
/* Speed up animations */
-webkit-animation-duration: 0.55s;
animation-duration: 0.55s;
-webkit-animation-timing-function: ease;
animation-timing-function: ease;
}
Wrote an article with more detail and a download if anyones interested:
article: http://bootbites.com/tutorials/bootstrap-dropdown-effects-animatecss
Hope that’s helpful & this second write up has the level of detail that’s needed
Tom
Intro
As of the time of writing, the original answer is now 8 years old. Still I feel like there isn't yet a proper solution to the original question.
Bootstrap has gone a long way since then and is now at 4.5.2. This answer addresses this very version.
The problem with all other solutions so far
The issue with all the other answers is, that while they hook into show.bs.dropdown / hide.bs.dropdown, the follow-up events shown.bs.dropdown / hidden.bs.dropdown are either fired too early (animation still ongoing) or they don't fire at all because they were suppressed (e.preventDefault()).
A clean solution
Since the implementation of show() and hide() in Bootstraps Dropdown class share some similarities, I've grouped them together in toggleDropdownWithAnimation() when mimicing the original behaviour and added little QoL helper functions to showDropdownWithAnimation() and hideDropdownWithAnimation().
toggleDropdownWithAnimation() creates a shown.bs.dropdown / hidden.bs.dropdown event the same way Bootstrap does it. This event is then fired after the animation completed - just like you would expect.
/**
* Toggle visibility of a dropdown with slideDown / slideUp animation.
* #param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
* #param {boolean} show Show (true) or hide (false) the dropdown menu.
* #param {number} duration Duration of the animation in milliseconds
*/
function toggleDropdownWithAnimation($containerElement, show, duration = 300): void {
// get the element that triggered the initial event
const $toggleElement = $containerElement.find('.dropdown-toggle');
// get the associated menu
const $dropdownMenu = $containerElement.find('.dropdown-menu');
// build jquery event for when the element has been completely shown
const eventArgs = {relatedTarget: $toggleElement};
const eventType = show ? 'shown' : 'hidden';
const eventName = `${eventType}.bs.dropdown`;
const jQueryEvent = $.Event(eventName, eventArgs);
if (show) {
// mimic bootstraps element manipulation
$containerElement.addClass('show');
$dropdownMenu.addClass('show');
$toggleElement.attr('aria-expanded', 'true');
// put focus on initial trigger element
$toggleElement.trigger('focus');
// start intended animation
$dropdownMenu
.stop() // stop any ongoing animation
.hide() // hide element to fix initial state of element for slide down animation
.slideDown(duration, () => {
// fire 'shown' event
$($toggleElement).trigger(jQueryEvent);
});
}
else {
// mimic bootstraps element manipulation
$containerElement.removeClass('show');
$dropdownMenu.removeClass('show');
$toggleElement.attr('aria-expanded', 'false');
// start intended animation
$dropdownMenu
.stop() // stop any ongoing animation
.show() // show element to fix initial state of element for slide up animation
.slideUp(duration, () => {
// fire 'hidden' event
$($toggleElement).trigger(jQueryEvent);
});
}
}
/**
* Show a dropdown with slideDown animation.
* #param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
* #param {number} duration Duration of the animation in milliseconds
*/
function showDropdownWithAnimation($containerElement, duration = 300) {
toggleDropdownWithAnimation($containerElement, true, duration);
}
/**
* Hide a dropdown with a slideUp animation.
* #param {JQuery} $containerElement The outer dropdown container. This is the element with the .dropdown class.
* #param {number} duration Duration of the animation in milliseconds
*/
function hideDropdownWithAnimation($containerElement, duration = 300) {
toggleDropdownWithAnimation($containerElement, false, duration);
}
Bind Event Listeners
Now that we have written proper callbacks for showing / hiding a dropdown with an animation, let's actually bind these to the correct events.
A common mistake I've seen a lot in other answers is binding event listeners to elements directly. While this works fine for DOM elements present at the time the event listener is registered, it does not bind to elements added later on.
That's why you are generally better off binding directly to the document:
$(function () {
/* Hook into the show event of a bootstrap dropdown */
$(document).on('show.bs.dropdown', '.dropdown', function (e) {
// prevent bootstrap from executing their event listener
e.preventDefault();
showDropdownWithAnimation($(this));
});
/* Hook into the hide event of a bootstrap dropdown */
$(document).on('hide.bs.dropdown', '.dropdown', function (e) {
// prevent bootstrap from executing their event listener
e.preventDefault();
hideDropdownWithAnimation($(this));
});
});
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideUp();
});
This code works if you want to reveal dropdowns on hover.
I just changed the .slideToggle to .slideDown & .slideUp, and removed the (400) timing
Here is a nice simple solution using jQuery that works nicely:
$('.dropdown-toggle').click(function () {
$(this).next('.dropdown-menu').slideToggle(300);
});
$('.dropdown-toggle').focusout(function () {
$(this).next('.dropdown-menu').slideUp(300);
})
The slide animation toggle occurs on clicking and it always slides back up on losing focus.
Alter the 300 value to anything you want, the lower the number the faster the animation.
Edit:
This solution will only work for desktop views. It will need some further modification in order to display nicely for mobile.
I recommend using transform instead of max-height, it is faster, and GPU accelerated.
For Bootstrap 5 add the following CSS:
.dropdown .dropdown-menu {
-webkit-transition: all 0.32s;
-moz-transition: all 0.32s;
-ms-transition: all 0.32s;
-o-transition: all 0.32s;
transition: all 0.32s;
display: block;
overflow: hidden;
opacity: 0;
transform: translateX(-25%) scaleY(0);
transform-origin: top;
}
.dropdown-menu.show {
opacity: 1;
transform: translateX(-25%) scaleY(1);
}
BOOTSTRAP 3 REFERENCE
Added because I keep getting caught by the solution in this thread and it stuffs me up every time.
Basically the BS dropdown immediately removes the .open class from the parent, so sliding up does not work.
Use the same bit as other solutions for slideDown();
// ADD SLIDEUP ANIMATION TO DROPDOWN //
$('.dropdown').on('hide.bs.dropdown', function(e){
e.preventDefault();
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300, function(){
$(this).parent().removeClass('open');
});
});
For Bootstrap 3, this variation on the answers above makes the mobile slideUp() animation smoother; the answers above have choppy animation because Bootstrap removes the .open class from the toggle's parent immediately, so this code restores the class until the slideUp() animation is finished.
// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970
$('.dropdown')
.on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
})
.on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
$(this).parent().removeClass('open');
});
})
.on('hidden.bs.dropdown', function() {
$(this).addClass('open');
});
Key differences:
In the hide.bs.dropdown event handler I'm using .stop()'s default value (false) for its second argument (jumpToEnd)
The hidden.bs.dropdown event handler restores the .open class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp() animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open class from its parent.
Methods are chained together because the selector for each event handler is the same
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300, function(){
$(this).parent().removeClass('open');
});
i have just replace .slideUp with .slideToggle and its working fine for up and down.
This simply worked fine for me.
.dropdown-menu {
transition: all linear .5s;
}
.dropdown-menu.show {
display: block;
transition: all linear .5s;
}
It works in Bootstrap 5 and React-Bootstrap...
.dropdown-menu {
display: block;
transform-origin: top;
transform: scaleY(0);
opacity: 0;
overflow: hidden;
transition: all 0.3s ease-in-out;
-webkit-transition: all 0.3s ease-in-out;
}
.dropdown.show .dropdown-menu {
opacity: 1;
transform: scaleY(1);
overflow: visible;
}
Im trying to animate a large image so it changes dimensions, starts at (200x116)px and becomes (400x232)px on click and then would revert back to (200x116)px if clicked again,
Here's a link to the code: http://jsfiddle.net/edddotcom/FMfC4/1/
HTML:
<img id="imgtab" src="http://cloudsmaker.com/hipsterwall/img/salto-al-norte.jpg">
CSS:
#imgtab {
position:relative;
}
JavaScript:
$(document).ready(function () {
$("#imgtab").toggle(function () { //fired the first time
$("#imgtab").animate({
width: "200px"
height: "116px"
});
}, function () { // fired the second time
$("#imgtab").animate({
width: "400px"
height: "232px"
});
});
});
Clicking the image should make it animate from small to large but it doesn't seem to change. Can anyone suggest what to change and tell me what i'm doing wrong?
if you simply want to toggle on click, try below
$(document).ready(function () {
var small={width: "200px",height: "116px"};
var large={width: "400px",height: "232px"};
var count=1;
$("#imgtab").css(small).on('click',function () {
$(this).animate((count==1)?large:small);
count = 1-count;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="imgtab" class='small' src="http://cloudsmaker.com/hipsterwall/img/salto-al-norte.jpg">
OR
you can also use the duration parameter of addClass and removeClass functions available in jQuery-ui widgets library. i.e.
$(document).ready(function () {
var count=1;
$("#imgtab").on('click', function () {
var $this = $(this);
$this.removeClass('small, large',400);
$this.addClass((count==1)?'large':'small',400);
count = 1-count;
})
});
where .small and .large css classes are :
.small{
width:200px;
height:116px;
}
.large{
width:400px;
height:232px;
}
see this working fiddle.
NOTE: you will need reference of jQuery UI library also, cause duration parameter of addClass and removeClass is available there only.
You are missing comma between object properties passed as a argument in animate method.
$(document).ready(function () {
$("#imgtab").toggle(function () { //fired the first time
$("#imgtab").animate({
width: "200px",//HERE
height: "116px"
});
}, function () { // fired the second time
$("#imgtab").animate({
width: "400px",//HERE
height: "232px"
});
});
});
EG: http://jsfiddle.net/dFU9P/
Here is a simple way you can achieve your animation effect without having to use jQuery's animate and instead use CSS animations. I don't know what browsers you need to support, but it is still nice to see how it can be done in different ways.
HTML:
<img id="imgtab" src="http://cloudsmaker.com/hipsterwall/img/salto-al-norte.jpg">
CSS:
img {
height: 200px;
width: 116px;
-webkit-transition: all .4s ease-in; //added vendor prefixes for older browsers
-moz-transition: all .4s ease-in; //first parameter decides what properties to animate
-m-transition: all .4s ease-in; // second is duration
-o-transition: all .4s ease-in; //3rd is the timing-function
transition: all .4s ease-in;
}
.fullSize {
height: 400px;
width: 232px;
}
jQuery:
$('#imgtab').on('click', function(e) {
$(this).toggleClass('fullSize');
});
And here is the fiddle http://jsfiddle.net/AtQwM/. Feel free to mess around with the transition parameters for different effects!
Toggle offers two states for one event but any animation using it ends up with display:none. You therefore need to use your own toggling mechanism using a variable to control the state of the image:
$(document).ready(function() {
var imgSmall = false
$('#imgtab').on('click',function() {
$("#textab").toggle(20);
if ( imgSmall ) {
$('#imgtab').animate({width:"400px",height:"232px"});
imgSmall = false
} else {
$('#imgtab').animate({width:"200px",height:"116px"});
imgSmall = true
}
});
});
http://jsfiddle.net/FMfC4/3/
Instead of placing the new image dimension in the code they could be data-attributes.
http://jsfiddle.net/FMfC4/8/
<img class="imgtab" src="http://cloudsmaker.com/hipsterwall/img/salto-al-norte.jpg" data-width="400" data-height="200">
(function($) {
$.fn.imageSizer = function() {
var originalSize = {
width: this.width(),
height: this.height()
};
this.on('click', function() {
var newSize = {
width: $(this).data('width'),
height: $(this).data('height')
};
var currentSize = ($(this).width() == newSize.width) ? originalSize : newSize;
$(this).animate(currentSize);
});
}
})(jQuery);
$(document).ready(function() {
$(".imgtab").imageSizer();
});
I'd like to add a slide & fade effect to a DIV, with purely Javascript, using "onclick".
The code is here: http://jsfiddle.net/TCUd5/
The DIV that has to slide has id="pulldown_contents_wrapper".
This DIV is contained in a SPAN, that also triggers it:
<span onclick="toggleUpdatesPulldown(event, this, '4');" style="display: inline-block;" class="updates_pulldown" >
<div class="pulldown_contents_wrapper" id="pulldown_contents_wrapper">
And I think the JS code that controls the SPAN onclick is:
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.className= 'updates_pulldown_active';
showNotifications();
} else {
element.className='updates_pulldown';
}
}
If it is not possible to make it with pure JS, do you have an idea how could I do it with Mootools? (*I'd like to use only pure JS or the Mootols framework).
I have tried to implement the code from: why javascript onclick div slide not working? but with no results.
Thanks a lot.
I have managed to make it with Mootools, but I can't figure it out how to add a slide & fade effect, and a delay on mouseout
window.addEvent('domready', function() {
$('updates_pulldown').addEvents({
mouseenter: function(){
$('updates_pulldown').removeClass('updates_pulldown').addClass('updates_pulldown_active')
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
physics: 'pow:in:out',
transition: Fx.Transitions.Bounce.easeOut // This could have been also 'bounce:out'
}).show();
},
mouseleave: function(){
$('pulldown_contents_wrapper').set('tween', {
duration: 1000,
delay: 1000,
}).hide();
$('updates_pulldown').removeClass('updates_pulldown_active').addClass('updates_pulldown')
},
});
});
var toggleUpdatesPulldown = function(event, element, user_id) {
showNotifications();
}
Any idea?
jQuery is a lot easier, but with pure javascript you can do it.
In the CSS you'll need to use transitions
#thing { position:relative;
top: 0px;
opacity: 0.8;
-moz-transition: top 1s linear, opacity 1s linear;
-webkit-transition: top 1s linear, opacity 1s linear;
}
then in the javascript when you change the position of the element, it should change via the css transitions.
var toggleUpdatesPulldown = function(event, element, user_id) {
if( element.className=='updates_pulldown' ) {
element.style.top = someValue; //something like '100px' will slide it down 100px
element.style.opacity = '1.0'; //will fade the content in from 0.8 opacity to 1.0
element.className= 'updates_pulldown_active';
showNotifications();
EDIT - provided jQuery code
call the jQuery library, most easily done from the google hosting
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
make the hover function
$(document).ready(function() {
$('.updates_pulldown').hover( //first function is mouseon, second is mouseout
function() {
$(this).animate({top: '50px'}).animate({opacity: '1.0'});
},
function() { //delay 1000 milliseconds, animate both position and opacity
$(this).delay(1000).animate({top: '0px'}).animate({opacity: '0.5'});
}
)
})
the function timing will be the same as whatever you set it to in the css with transition tags. using 'this' instead of the class name again makes sure that the effect only occurs on the specific instance of the class that is hovered over. im not sure if this animation is exactly what you were asking for, but if i understand the question correctly then the main functionality will work for you. just change the numbers and such to fit your needs.