toggle width resize animation - jquery - javascript

I have <div id="test"></div>and <a id="trigger"></a>. Div has width 300px. I want the div to re size it's width to 100px when user click trigger and want to re size to previous size when user again click the trigger. How can i make this using jquery??
Thanks in advance...:)
blasteralfred

Assign a variable of 1 for click and 0 for unclick and then use the .click function as follows:
$(document).ready(function(){
TriggerClick = 0;
$("a#trigger").click(function(){
if(TriggerClick==0){
TriggerClick=1;
$("div#test").animate({width:'100px'}, 500);
}else{
TriggerClick=0;
$("div#test").animate({width:'300px'}, 500);
};
});
});
UPDATE - BETTER ANSWER
I made this suggestion awhile back; but believe there is a more elegant and pragmatic approach to solving this. You could use CSS transitions and have jquery simply add/remove a class that initiates the transition:
Working Fiddle:
https://jsfiddle.net/2q0odoLk/
CSS:
#test {
height: 300px;
width: 300px;
background-color: red;
/* setup the css transitions */
-webkit-transition: width 1s;
-moz-transition: width 1s;
transition: width 1s;
}
#test.small {
width: 100px;
}
jQuery:
$("a#trigger").on('click', function(){
$("div#test").toggleClass('small');
});

This is Html Part of this toggle:
<div id="start">
<div class="slide"></div>
</div>
This is CSS part for that:
<style>
#start{ margin-bottom:60px; display:block; font-size:16px; width:14px; height:79px; position:relative; top:25px; line-height:21px; color:#F0F; background:url(./start1.JPG) left top no-repeat;}
.slide{ background:#98bf21; max-width:500px; width:100; height:100px;position:absolute; left:14px;}
</style>
<script>
$(document).ready(function()
{
function tog()
{
var w = $(".slide").css('width');
if(w=='0px')
{
$(".slide").animate({
width:500
});
}
else
{
$(".slide").animate({
width:0
});
}
}
$("#start").click(function()
{
tog();
});
});
</script>

You need to bind an .click()-Event to #trigger and toggle the animation.
http://api.jquery.com/toggle/
http://api.jquery.com/animate/

Something like this should to the trick.
$('#trigger').bind('click', function() { $('#test').animate({"width": "100px"}, "slow"); })

For those looking for a shorter but yet working version you could do this:
$('a#trigger').on('click', function(e) {
e.preventDefault();
var w = ($('div#test').width() == 300 ? 100 : 300);
$('div#test').animate({width:w},150);
});
The shortest version:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$('div#test').animate({width:($('div#test').width() == 300 ? 100 : 300)},150);
});
On a function:
function toggleWidth(target, start, end, duration) {
var w = ($(target).width() == start ? end : start);
$(target).animate({width:w},duration);
return w;
}
Usage:
$('a#trigger').on('click', function(e) {
e.preventDefault();
toggleWidth($("div#test"), 300, 100, 150);
});
Finally on a JQuery.fn.extend function:
jQuery.fn.extend({
toggleWidth: function(start, end, duration) {
var w = ($(this).width() == start ? end : start);
$(this).animate({width:w},duration);
return w;
}
});
Usage:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$("div#test").toggleWidth(300, 100, 150);
});

Related

How do I add fadein or fadeout animation when doing addClass or removeClass on scroll

I am basically trying to change classes of a bootstrap 4 navbar with the following jquery when there is a scroll but this doesnt seem to be working
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$(".navbar")
.removeClass("navbar-dark")
.fadeOut("fast");
$(".navbar")
.addClass("navbar-light bg-light")
.fadein("slow");
} else {
$(".navbar")
.removeClass("navbar-light bg-light")
.fadeOut("fast");
$(".navbar")
.addClass("navbar-dark")
.fadein("slow");
}
});
You don't need two classes. Only Default styles and a special class.
Don't use jQuery to do animations - Use CSS3 and transition instead
Use jQuery's .toggleClass() Method
Cache your selector Elements! The worst thing you can do is on every scroll-tick query the entire DOM to go search for a .class element/s - that's a too expensive operation.
const $navbar = $('.navbar'); // Cache your elements!!
$(window).on('scroll', function() {
const st = $(window).scrollTop();
$navbar.toggleClass('is-scrolled', st >= 100);
});
body {
margin: 0;
height: 300vh; /* DEMO to force scrollbars */
}
/* DEFAULT STYLE */
.navbar {
position: sticky;
top: 0;
width: 100%;
transition: 0.4s;
background: gold;
}
/* SCROLLED STYLE */
.navbar.is-scrolled {
background: #888;
}
<div class="navbar">NAVBAR</div>Scroll down...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
The .fadeOut() function of jQuery has a duration and a complete parameter. The complete parameter can be a function which is called whenever the fade out is finished. This way you can do something after the fadeOut is finished, like do the fadeIn that you want.
See the example below.
var $navbar = $(".navbar");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$navbar
.removeClass("navbar-dark")
.stop(true, true)
.fadeOut("fast", function() {
$navbar
.addClass("navbar-light bg-light")
.fadeIn("slow");
});
} else {
$navbar
.removeClass("navbar-light bg-light")
.stop(true, true)
.fadeOut("fast", function() {
$navbar
.addClass("navbar-dark")
.fadeIn("slow");
});
}
});
But I would encourage to use CSS transitions for this cause since they are way easier to work with and most importantly, more performant than jQuery fade in and out.
Edit
As Roko suggested, you should use the .stop() function to stop any current animation on the element where a fadeIn or fadeOut is running.

jquery - moving multiple instances of div across screen at random Y-position

I want to detect clicks and move elements from off-screen right to off-screen left with jquery.
I achieved the general idea already (fiddle) but only for one div, once.
HTML:
<div class = "outer">
<div id = "box">
</div>
</div>
CSS:
body {
overflow-x: hidden;
height: 500px;
}
#box{
height: 100px;
width: 100px;
background: #FF00FF;
position: absolute;
right: -100px;
}
JS:
$(document).ready(function(){
$(document).click(function(){
var bodyHeight = document.body.clientHeight;
var randPosY = Math.floor((Math.random()*bodyHeight));
$('#box').css('top', randPosY);
$("#box").animate({left: '-100px'}, 5000);
});
});
How can make a new instance div appear (at random y-position) per click on the document?
My random y-position is calculated in jQuery the following way, but gets its value from my css height: 500px; - how can I make this value responsive?
Use a function constructor to add object instances of a div, where each one uses .box class instead of #box:
fiddle
function SlidingDiv(bodyHeight){
this.randPosY = Math.floor((Math.random()*bodyHeight));
this.$div = $("<div>").addClass('box').appendTo('.outer');
};
SlidingDiv.prototype.slide = function(){
this.$div.css('top', this.randPosY);
this.$div.animate({left: '-100px'}, 5000);
};
$(document).ready(function(){
$(document).click(function(){
var bodyHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var div = new SlidingDiv(bodyHeight);
div.slide();
});
});
Edit: To remove divs, you could try the complete function:
SlidingDiv.prototype.slide = function() {
this.$div.css('top', this.randPosY);
this.$div.animate({
left: '-100px',
duration: 5000,
complete: function() { this.$div.remove(); }.bind(this)
});
};

how to return animation to it's original size and position on a click

I am relatively new to all this so if you see anything I am doing wrong, or anyways to simplify any code please do not hesitate to say.
I have the following code to enlarge the div element:
var profilePostsClick = function () {
$('.largeBox, .smallBox, .longBox').click(function () {
$(this).animate({
width: '100%',
height: '40%'
}, 200);
$('.closePost', this).removeClass('closePostHide');
});
};
$(document).ready(profilePostsClick);
https://jsfiddle.net/jvkhmpbt/
I am wanting to close each div when the cross is clicked, returning it to it's original size and positioning (with height: auto if feasible).
Aslo is there a way to make it so each div opens above the smaller ones? (like the top left div does, i am aware this is because of it's positioning)
Thanks
You can do like following way by adding and removing class
JQuery:
$('.largeBox, .smallBox, .longBox').click(function (e) {
e.preventDefault();
$(this).addClass('increaseSize');
$('.closePost', this).removeClass('closePostHide');
});
$('.glyphicon-remove').click(function (e) {
e.stopPropagation()
$('.glyphicon-remove').parent().parent().removeClass('increaseSize');
$('.closePost', this).addClass('closePostHide');
});
CSS:
.increaseSize{
width: 100%;
height: 40%;
}
Check Fiddle Here.
You could save the animation properties/values in an cache-object and restore them after your animation.
http://jsfiddle.net/jvkhmpbt/4/
var animationResetCache = [];
var saveValues = function (node) {
animationResetCache.push({
node: node,
width: node.css('width'),
height: node.css('height')
});
};
var restoreValues = function (node) {
for (var i = 0; i < animationResetCache.length; ++i) {
var item = animationResetCache[i];
if (item.node.is(node)) {
return item;
}
}
};
var profilePostsClick = function () {
$('.largeBox, .smallBox, .longBox').click(function (e) {
var $this = $(this);
if ($this.hasClass('open')) return;
saveValues($this);
$this.addClass('open').animate({
width: '100%',
height: '40%'
}, 200);
$this.find('.closePost').removeClass('closePostHide');
});
$('.closePost').click(function () {
var $parent = $(this).parent('.largeBox, .smallBox, .longBox');
if ($parent.hasClass('open')) {
var cachedValues = restoreValues($parent);
$parent.animate({
width: cachedValues.width,
height: cachedValues.height
}, function () {
$parent.removeClass('open');
});
$parent.find('.closePost').addClass('closePostHide');
}
});
};
$(document).ready(profilePostsClick);
I think it's easier to use a toggle and do the animation in CSS3
$("img").click(function(){
$(this).toggleClass('expanded');
});
I would suggest to add one more identical class to each of smallBox,largeBox and longBox which will be called parentd to identify parent div and animate it back and add below js:
DEMO
$('.closePost').on('click',function(e)
{
$(this).closest('.parentd')
.animate({
width: '40%',
height: 'auto'
},200).removeAttr('style');
$(this).addClass('closePostHide');
e.stopPropagation();
});
If we continue on Rover his answer, we can use the switchClass function in jQuery Ui. (source)
This function let's you switch the classes of an object, creating an animation in the difference between those classes.
Example code: jsFiddle
<div class="large"></div>
CSS:
.large{
width: 100%;
height: 200px;
background-color: red;
}
.small {
width: 10%;
height: 50px;
background-color:green;
}
JS:
$("div").switchClass("large","small",500);

How to create a floating div with jQuery

When the mouse is over an element A of a certain class , another floating div B, which contains a link, should appear. B should disappear as soon as the mouse has left A and B.
How can I do this with jQuery?
jsFiddle
var container = $('#container');
var area = $('.area'); // this is A
var position = area.offset();
var floating = $("<div />", {
css : { "position" : "absolute",
"top" : position.top - 30,
"left" : position.left + 20,
"border" : "1px solid #000",
"padding" : "5px",
"display" : "none",
"z-index" : "100",
"background-color" : "#F00"
}
})
.text('Hello World'); // this is B
container.css('position', 'relative');
container.append(floating);
function show() {
floating.show();
}
function hide() {
floating.hide();
}
area.on('mouseenter', show);
area.on('mouseleave', hide);
floating.on('mouseenter', function(event) {
console.log("floating: mouseenter");
area.off('mouseenter', show);
area.off('mouseleave', hide);
});
floating.on('mouseleave', function(event) {
console.log("floating: mouseleave");
area.on('mouseenter', show);
area.on('mouseleave', hide);
});
My problem is that evertime the mouse enters B, B disappears already. I need to do this with jQuery, not only CSS.
I'm not sure why you have to put the floating div in the jQuery. This is probably how I would achieve something similar to what you want.
http://jsfiddle.net/A2gFb/6/
Just put the hidden float in the HTML,
<div class="area">luptatum zzril
<div class="fixed">Hello World!</div>
</div>
with proper CSS set.
.area {
position: relative;
color: #0F0;
font-weight: bold;
/* you may want to set the width/height here as well*/
}
.fixed {
position: absolute;
top: 20px;
left: 20px;
border: 1px solid black;
padding: 5px;
z-index: 100; /* Thanks Diego for pointing out the typo here */
background-color: red;
display: none;
}
And the jQuery would be as simple as this:
$(".area").mouseenter( function() {
$(".fixed").show();
});
$(".area").mouseleave( function() {
$(".fixed").hide();
});
The major problem you are having is that the mouseleave event for your green text is firing before the mouseenter for your floating div. To fix this I made a variable to track the mouse being in the float and used a setTimeout in the hide() function to check for this variable after 100 ms. You could probably go lower if you were worried about the delay. Here's the fiddle.
At the top of the javascript:
var inFloat = false;
The hide() function becomes:
function hide() {
setTimeout(function(){
if (!inFloat)
floating.hide();
},100);
}
And your floating mouse events become:
floating.on('mouseenter', function(event) {
inFloat = true;
});
floating.on('mouseleave', function(event) {
inFloat = false;
floating.hide();
});
You still have the issue that the floating div has a fixed position that isn't related to the mouse position, so it may be awkward to hover over the link and then move to floating div at times.
just add:
floating.on('mouseenter', show);
floating.on('mouseleave', hide);
it works on jsFiddle.
By the way, I suggest you to not use "show" and "hide" as function name since they already exist in jQuery. showTooltip and hideTooltip can be good names.

jQuery slide out animation

I am working on a slide out bar for a project I am working on and I am having a hard time getting an animation to work.
My Goal is to have it slide out from left to right not appear from the top like it is now.
Below is my jQuery code as well as my jsfidde
Thanks in advance
George
http://jsfiddle.net/tXye8/
$(document).ready(function(){
var $button = $('#sideoutButton');
var $contain = $('#slideoutContain');
var containWidth = $('#slideoutContain').width();
//Hide the box
$contain.hide();
//Hide or show the container on button click
$button.click(function(){
if ($contain.is(":visible")) {
$contain.hide();
$button.css("left", 0);
}
else {
$contain.show(400, buttonMove());
}
});
function buttonMove(){
$button.css("left", function(value) {
return 0 + containWidth;
});
}
});
If you know how wide it's supposed to be, you can achieve this with CSS:
#mycontainer {
width: 0;
transition: width 400ms ease;
}
#mycontainer.expand {
width: 400px; //or whatever your width is
}
and just use JS/jQuery to toggle a class on #mycontainer

Categories

Resources