jquery animate() toggle without hiding the element - javascript

Is there a way to toggle a single CSS property using the animate() function without hiding it?
Something like this;
$(".block").animate({ 'border-width': 'toggle' }, 1000);
I cannot use the toggleClass(), addClass() or removeClass(). The reason for this is that it has an unwanted effect on the size of the element that is animated (see JSFiddle).
You can find a JSFiddle here.
What I can think of is this;
if(parseInt($(".block").css('border-width'))) {
$(".block").animate({ 'border-width': '0'});
}
else {
$(".block").animate({ 'border-width': '100px'});
}
..Or something like this by adding a class to the element. But I would prefer not to use an if statement. I wonder if this is possible in a single line of code. Feels like it should be.

try using this, in your css:
.block1,
.block2 {
display: inline-block;
vertical-align: top;
color: white;
height: 100%;
width: 50%;
transition: all, 1s;
}
.no-border-top {
border-top-width: 0;
}
then simply toggle no-border-top class, you can see it here

You can use variables to define toggle effect:
var currentBorderW = 0;
$('.block1').on('click', function(){
var nextBorderW = parseInt($(this).css('border-width'));
$(this).animate({ 'border-width': currentBorderW + 'px' }, 1000);
currentBorderW = nextBorderW;
});
Here is working jsFiddle.

Does this do what you want?
$('.block1').on('click', function(){
$(this).animate({ 'border-width': '-=100px' }, 1000);
});
$('.block2').on('click', function(){
$(this).children().first().show();
$(this).toggleClass('borderTop', 1000);
});
JS Fiddle for this code sample
Everything else is the same: your CSS, HTML, etc. I only changed the property border-width to have a value of -= 100px.
I used the -= operator, per the jQuery API docs:
Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.
EDIT: To make it slide back in again, see this example on JSFiddle
(function(){
var clickCount=0;
$('.block1').click(function(){
if (clickCount%2==0) {
$(this).animate({ 'border-width': '-=100px' }, 1000);
}
else {
$(this).animate({ 'border-width': '+=100px' }, 1000);
}
clickCount++;
});
})();
$('.block2').on('click', function(){
$(this).children().first().show();
$(this).toggleClass('borderTop', 1000);
});

Related

jQuery slide animation on existing divs after prependTo

I have this semi-slider-style UI where new terms are added in from the left: http://jsfiddle.net/v4v5cvkz/. I'm using the jQuery prependTo function to do this. My issue is that I want the terms that are already displayed to perform an animated slide to the right when a new term gets added, rather than suddenly "appear" in the correct position. I did try adding a "displayed" class to terms that had successfully shown up, and tried adding a slide-to-right animation after that, but that didn't quite achieve the effect I was going for (the "displayed" objects were moved much further to the right than I expected).
Here is the problematic code (you'll probably want to view the fiddle to see it in context though):
function addToStream(term, delay) {
setTimeout(function(){
$("<div />")
.addClass("stream_term")
.html(term)
.css({
opacity: 0
})
.prependTo("#stream_terms")
.animate({opacity:1},
{ duration: 1000,
complete: function() {
$(this).addClass("displayed");
}
});
}, delay);
}
Any help here would be greatly appreciated. Thank-you!
*Note: I have access to jQuery UI in my code, though it isn't linked in the fiddle. Also, if anyone knows of a plugin that can do this sort of thing better than I can, please let me know. The closest one I was able to find was Fraction Slider, but I didn't find it obvious how to create a similar UI with it (it might also be overkill for my purposes).
Here's a way to do it:
function addToStream(term, delay) {
setTimeout(function(){
var newDiv = $("<div />");
newDiv.addClass("stream_term")
.html(term)
.css({
opacity: 0,
display: 'none'
}).prependTo("#stream_terms");
var width = newDiv.width();
var height = newDiv.height();
newDiv.css({
width: 0,
height: height,
display: 'inline-block'
})
.animate({
width: width,
margin: '0 10px',
padding: '5px 10px'
}, 1000)
.animate({opacity: 1}, 1000, function(){
$(this).addClass("displayed");
});
}, delay);
}
It also needs the following CSS changes:
.stream_term {
padding: 0;
margin: 0;
overflow: hidden;
}
DEMO: http://jsfiddle.net/StathisG/hqg29p6r/1/

jQuery: change background color after animation completes

I'm having trouble with my jQuery right now. What I want is that the background color is changed after the animation completes. I haven't been able to figure out how to make it work. I don't understand there are no console errors.
http://jsfiddle.net/4pmzf/
jQuery:
$("#slider").toggle(function () {
$(this).animate({
"height":"100px"
}, 1000).addClass('red');
}, function () {
$(this).animate({
"height":"20px"
}, 1000).removeClass('red');
});
CSS
#slider {
width: 100%;
background: black;
height: 20px;
cursor: pointer;
}
.red {
background: red;
}
This is a specificity issue. The initial background declaration has a higher specificity because it was declared with an id. You could solve this by overwriting it with a more specific selector:
UPDATED EXAMPLE HERE
#slider.red {
background:red;
}
The initial selector, #slider, has a specificity of 100.
The new selector, #slider.red, has a slightly higher specificity of 110.
Aside from this, the background really isn't being changed after the animation completes. I'd suggest adding a callback/complete function to the animation(s)..
CALLBACK EXAMPLE HERE
$("#slider").toggle(function () {
$(this).animate({
"height":"100px"
}, 1000, function(){
$(this).css('background','red');
});
}, function () {
$(this).animate({
"height":"20px"
}, 1000, function(){
$(this).css('background','');
});
});
Also.. rather than changing classes, it's probably better to just modify the CSS.

change css of body on mouseover

I want to get an highlighting effect on some various div container while the rest of the site should be dampened down in opacity including the background-image.
Any idea?
Why does this code not work? tried .hover() instead of .mouseover() too but the function won't react on any input...
$(function () {
$('body').mouseover(function () {
$('body').prop({
"background-color": "red";
});
});
});
Another try would be to set a frame around the body tag in the html and then set props to that frame while the hovered frame is in normal state but I have no idea how to do this. Just beginning with js dev. :)
EDIT: did a fail...
$(function () {
$('body').mouseover(function () {
$('body').css({
"opacity": "0.3";
});
});
});
should be that way...
any way to apply the opacity to the background image too?!
fiddle Demo
Use .css()
Set one or more CSS properties for the set of matched elements.
$(function () {
$('body').mouseover(function () {
$(this).css({
"background-color": "red"
});
//or $(this).css("background-color","red");
});
});
this
.prop()
Set one or more properties for the set of matched elements.
.prop() will set the property for a particular element. In your case you have to use .css() to set the style. Please read .prop() and .css() to see the difference.
Try this,
$(function(){
$('body').mouseover(function(){
$(this).css({"background-color":"red"});
});
});
DEMO
Here's a FIDDLE
body {
background: gray;
min-height: 1000px; /* For demo purposes */
}
css
$(function() {
$('body').on('mouseover', function() {
$(this).css({ backgroundColor: 'red' });
});
});
animate
$(function() {
$('body').on('mouseover', function() {
$(this).animate({ backgroundColor: 'red' }, 600);
});
});
*Note: For some reason it doesn't work with jQuery 1.x(edge).
I think this is what you might want: a "dim" DIV element that adds a semi transparent black box on the entire page, that puts itself "below" the DIV you want to highlight, and then some javascript to turn it off and on, and rearrange the z indexes. The HTML would look something like this:
this is some text
<div id="div1" class="dimmable">hello</div>
<div id="div2" class="dimmable">goodbye</div>
<div id="dim"></div>
And then the JS:
$('div.dimmable').hover(function() {
$(this).css('z-index', 101);
$('#dim')
.css('z-index', 100)
.width($(window).innerWidth())
.height($(window).innerHeight())
.fadeIn();
}, function() {
var dimmable = $(this);
$('#dim').fadeOut({complete: function() {
dimmable.css('z-index', 99);
}});
});
You can see it working here.
A slight catch: the DIVs need to have position:relative, otherwise you can't change their z-indexes and you can't put them on top of the "dim" DIV. Also, anything with a higher z-index will not stay behind the "dim", of course, but you can just use higher numbers as a workaround.

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