Animated add / remove class - javascript

I'm looking to use fadeIn / Out when adding and removing of #left element in this code. Can you remove a class and animate that same element?
var window_width = $(window).width();
var scroll_amount = window_width * .75;
var left=$('#latest_wrapper');
$('#latest_wrapper #right').click(function() {
$('#left').removeClass('none');
$('#latest_wrapper').scrollTo('+=' + scroll_amount, 300);
});
$('#latest_wrapper #left').click(function() {
$('#latest_wrapper').scrollTo('-=' + scroll_amount, 300);
actual_left = left.scrollLeft() - scroll_amount;
if(actual_left <= 0){
$("#left").addClass('none');
}
});
# HTML page
<div id="latest_wrapper" data-offset="1">
<div id="left" class="arrow_wrapper none">
<i class="icon-angle-left"></i>
</div>
<div id="right" class="arrow_wrapper">
<i class="icon-angle-right"></i>
</div>
... more

Can you remove a class and animate that same element?
for that part of your question I can say:
$("#left").addClass('none').fadeOut();
but if you face some css that will make class none to be display none, then you must do animation first and then add your class.
$("#left").fadeOut('normal', function(){
$(this).addClass('none');
});
you can do the same with fadeIn()

Note: I'm assuming that you want to animate based on the properties being set in the CSS.
There are a bunch of options here, depending on your specific use-case.
The easiest and cleanest way would be to use CSS transitions along with your existing JavaScript:
http://jsfiddle.net/j85Az/
.arrow_wrapper {
transition: all 0.5s ease;
}
If you want to use JavaScript for this, you could use jQuery UI:
http://api.jqueryui.com/addclass/
If you don't want to use jQuery UI, you will most-likely need to do this manually using jQuery animate:
$('#left').animate({
//-- new CSS here
}, {
complete: function () {
$(this).removeClass('none');
}
});

Related

JavaScript/jQuery code optimization

I'm learning JavaScript and jQuery and currently I'm dealing with following code:
$("#hrefBlur0").hover(function() {
$("#imgBlur0").toggleClass("blur frame");
});
$("#hrefBlur1").hover(function() {
$("#imgBlur1").toggleClass("blur frame");
});
$("#hrefBlur2").hover(function() {
$("#imgBlur2").toggleClass("blur frame");
});
$("#hrefBlur3").hover(function() {
$("#imgBlur3").toggleClass("blur frame");
});
$("#hrefBlur4").hover(function() {
$("#imgBlur4").toggleClass("blur frame");
});
$("#hrefBlur5").hover(function() {
$("#imgBlur5").toggleClass("blur frame");
});
$("#hrefBlur6").hover(function() {
$("#imgBlur6").toggleClass("blur frame");
});
$("#hrefBlur7").hover(function() {
$("#imgBlur7").toggleClass("blur frame");
});
The code is supposed to remove blur effect from an image while I hoover a cursor on a href link on the website. I'm wondering if I can do it faster, with fewer lines of code.
I tried:
for (var i = 0; i < 8; i++) {
$("#hrefBlur" + i).hover(function() {
$("#imgBlur" + i).toggleClass("blur frame");
});
}
But that code doesn't work.
Here's the JS fiddle: link
You can set a class to the elements and select that class, for example let's say you want to use "blurMeContainer" for the container, you can do something like this:
$(".blurMeContainer").hover(function(el){
$(this).find("img").toggleClass("blur frame");
});
The trick is that you must be aware that jQuery applies the events to the element, so inside the events function, the "this" accessor is the element involved in the event, than you can use the $ function in the selector in order to have his corrispective jQuery element, and then you can use "find" method to find any img tag inside the jQuery element. Obviously this could work only if you have a single image in the container, if you need to identify only one image in a set of images inside a single container, assign a class to that image (IE: "blurMe") and change the code in this way:
$(".blurMeContainer").hover(function(el){
$(this).find(".blurMe").toggleClass("blur frame");
});
Use attributeStartsWith selector , that Selects elements that have the specified attribute with a value beginning exactly with a given string:
$('a[id^="hrefBlur"]').hover(function() {
$(this).find('img').toggleClass("blur frame");
});
Here's working fiddle
Although doing what your after can be done with JQuery. I personally think it's the wrong tool for the Job.
CSS, will do all this for you, in a much simpler way. No Javascript needed. With the added benefit of the browser optimisations.
.blurme {
filter: blur(3px);
cursor: pointer;
transition: color 2s, filter 1s;
}
.blurme:hover {
filter: none;
color: red;
font-weight: bold;
}
<span class="blurme">One</span>
<span class="blurme">Two</span>
<span class="blurme">Three</span>
<span class="blurme">Four</span>
<span class="blurme">Five</span>
<span class="blurme">Six</span>
<br>
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">

On scroll, logo color changes, but scrolling back up it stays the same

Im creating a fixed header where on load, the logo is flat white. On scroll, it changes to the full color logo.
However, when scrolling back to the top, it stays the same colored logo instead of going back to white.
Here's the code (and a pen)
$(function() {
$(window).scroll(function() {
var navlogo = $('.nav-logo-before');
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('.nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('.nav-logo-after').addClass('nav-logo-before');
}
});
});
http://codepen.io/bradpaulp/pen/gmXOjG
There's a couple of things here:
1) You start with a .nav-logo-before class but when the logo becomes black you remove that class and then try to get the same element using a class selector that doesn't exist anymore
2) removeClass('.nav-logo-before') is different than removeClass('nev-logo-before), notice the "." in the first selector.
3) You get the element using the $('.selector')in every scroll event, this can be a performance issue, it's better to cache them on page load and then use the element stored in memory
4) It's not a good practice to listen to scroll events as this can be too performance demanding, it's usually better to use the requestAnimationFrame and then check if the scroll position has changed. Using the scroll event it could happen that you scroll up really fast and the scroll event doesn't happen at 0, so your logo won't change. With requestAnimationFrame this can't happen
$(function() {
var navlogo = $('.nav-logo');
var $window = $(window);
var oldScroll = 0;
function loop() {
var scroll = $window.scrollTop();
if (oldScroll != scroll) {
oldScroll = scroll;
if (scroll >= 1) {
navlogo.removeClass('nav-logo-before').addClass('nav-logo-after');
} else {
navlogo.removeClass('nav-logo-after').addClass('nav-logo-before');
}
}
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.nav-logo-before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.nav-logo-after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo nav-logo-before">
</div>
<div class="space">
</div>
Dont need to add the dot . in front of the class name in removeClass and addClass:
Use this:
navlogo.removeClass('nav-logo-before')
Secondly, you are removing the class that you are using to get the element in the first place.
I have an updated codepen, see if this suits your needs: http://codepen.io/anon/pen/ZeaYRO
You are removing the class nav-logo-before, so the second time the function runs, it can't find any element with nav-logo-before.
Just give a second class to your navlogo element and use that on line 3.
Like this:
var navlogo = $('.second-class');
working example:
http://codepen.io/anon/pen/ryYajx
You are getting the navlogo variable using
var navlogo = $('.nav-logo-before');
but then you change the class to be 'nav-logo-after', so next time the function gets called you won't be able to select the logo using jquery as it won't have the '.nav-logo-before'class anymore.
You could add an id to the logo and use that to select it, for example.
Apart from that, removeClass('.nav-logo-before') should be removeClass('nav-logo-before') without the dot before the class name.
The problem is that you removes nav-logo-before and then you want to select element with such class but it doesn't exist.
I've rafactored you code to avert it.
Another problem is that you uses dot in removeClass('.before') while it should be removeClass('before') - without dot
$(function() {
var navlogo = $('.nav-logo');
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 1) {
navlogo.removeClass('before').addClass('after');
} else {
navlogo.removeClass('after').addClass('before');
}
});
});
body {
background-color: rgba(0,0,0,.2);
}
.space {
padding: 300px;
}
.before {
content: url(https://image.ibb.co/kYANyv/logo_test_before.png)
}
.after {
content: url(https://image.ibb.co/jYzFJv/logo_test_after.png)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img class="nav-logo before">
</div>
<div class="space">
</div>

How to animate navigation bar with jquery

I am creating a navigation bar see my fiddle: https://jsfiddle.net/dfbwp71u/
when I uses css() its working properly but when I use animate() its not giving me the result.
my html:
<nav class="navigation navbar-fixed-top">
</nav>
jquery:
$(window).scroll(function(){
// these conditional statements are working fine
if($(window).scrollTop() > 5)
{
$('.navigation').css({
'background-color':'#000'
});
}
else
{
$('.navigation').css({
'background-color':'#eee'
});
}
});
When I replace the .css() to animate() it stops giving me the result.
// ???
$('.navigation').animate({
'background-color':'#000'
});
Well you don't need animate for this unless you are not satisfied with css transition
DEMO
What I would do is just add a class called fixed and assign background-color:#000 like one below:
.fixed{
background-color:#000
}
and then I'll toggle this class based on the condition as below:
$(window).scroll(function(){
if($(window).scrollTop() > 5)
{
$('.navigation').addClass('fixed');
}
else
{
$('.navigation').removeClass('fixed');
}
});
The main thing we need to add here is transition property to .navigation and it will take care of rest:
.navigation
{
min-height:100px;
max-width:100%;
background-color:#eee;
transition: background 500ms;//change time accordingly
}
According to http://api.jquery.com/animate/
All animated properties should be animated to a single numeric value,
except as noted below; most properties that are non-numeric cannot be
animated using basic jQuery functionality (For example, width, height,
or left can be animated but background-color cannot be, unless the
jQuery.Color plugin is used)
so either use jquery-ui or jQuery.Color plugin
Add Jquery UI if you not add and change css property name 'background-color' to 'backgroundColor',
$(window).scroll(function(){
if($(window).scrollTop() > 5)
{
$('.navigation').animate({backgroundColor:'#eee'});
}
else
{
$('.navigation').animate({backgroundColor:'#000'});
}
});

What is the bet method of manipulating Classes for css animations via Javascript asa keyfame alternative

What is the bet method of manipulating Classes for css animations via Javascript asa keyfame alternative..
Hi peeps, Any help will be appreciated..
Iv'e been trying to get css animation transformation (#keyframes) with javascript control in a manner I can get my head round.
It occured to me that the the only listener that might be needed is already included (tranisionend). The coding I used is below.(a simple example: as a basis for more complex where css3 animations will be required).
Code
var classalt=0; var altidx=0; var transEnd = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend';
function animastage() {classalt=(altidx%2); var eaidx=parseInt(altidx/2);
if(classalt<1) {
if(eaidx==0) {$('.elealt').css({'background':'yellow', left:200+'px'}); }
if(eaidx==1) {$('.elealt').css({background:'green', left:0+'px'});}
$('#elemidX').addClass('elealt'); }
if(classalt>0) {
if(eaidx==0) {$('#elemidX').css({background:'blue', top:200+'px'});}
if(eaidx==1) {$('#elemidX').css({background:'red', left:300+'px',top:90+'px'});} /*Back To Start*/
$('#elemidX').removeClass('elealt');}
if(altidx==4) {return} /*Remove This line for continuation*/
altidx=(++altidx%5); /*Index to next Stage */
$('#elemidX').one(transEnd, function() { setTimeout('animastage()',10);});
HTML
<span id='dummy' class='elealt'></span>
<div id='elemidX' class='origelx'></div>
<div class="button" onclick='animastage()'>Try</div>
And CSS
/* Element to be Animated - initial position */
.origelx position:absolute;left:300px;top:90px;width:25px;height:25px
;background:red;transition: all 1s linear;}
.elealt {left:0;top:0;background:yellow;}
#dummy {display:none} /*?? Im order that .elealt is recognised*/
The problem however is changing the class properties as in a previous post:- Modifying CSS class property values on the fly with JavaScript / jQuery
In this case however it is required that both the added class and the original class need be modified(unless there is an alternative suggestion).
The reason I didnt bin my approach which I think is easy, if functional, is that the solution by Tejs Ref '2' to the previous post held some promise. Is there a quick fix I am missing.
See the solution I came Up with below
var classalt=0; var altidx=0; var transEnd = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend'; function animastage() {classalt=(altidx%2); var eaidx=parseInt(altidx/2); if(classalt<1) {alert(eaidx); if(eaidx==0) {$('.elealt').css({'background':'yellow', left:200+'px'}); } if(eaidx==1) {$('.elealt').css({background:'green', left:0+'px'});} $('#elemidX').addClass('elealt'); }
if(classalt>0) { if(eaidx==0) {$('#elemidX').css({background:'blue', top:200+'px'});} if(eaidx==1) {$('#elemidX').css({background:'red', left:300+'px',top:90+'px'});} /Back To Start/ $('#elemidX').removeClass('elealt');} if(altidx==4) {return} /Remove This line for continuation/ altidx=(++altidx%5); $('#elemidX').one(transEnd, function() { setTimeout('animastage()',10);});
Back again, Hope its Ok to answer my own question, however I believe I've now got a solution. The following (that works a treat) maybe a help to someone - any simpler solutions will still welcome!
CSS Nb : The Last Is As The Original class
* {margin:0px;padding:0px;border:none;}
.button { cursor:pointer; padding:4px 12px; border:1px solid gray;display:inline-block;}
/* Element to be Animated - initial position */
#elemidX {position:absolute;width:25px;height:25px;transition: all 2s linear;}
.eleorg {background:red;left:200px;top:90px;}
.stg1 {background:yellow;left:90px;top:90px;}
.stg2 {background:green;left:90px;top:200px;}
.stg3 {background: blue; left:200px;top:200px;}
.stg0 {background:red;left:200px;top:90px;}
HTML
<div id='elemidX' class='eleorg stg1 stg2 stg3 stg0'></div>
<div class="button" onclick='aniloc=0;animastage()'>Try</div>
<div class="button" onclick='aniloc=1;'>Stop</div>
And the Code
var transEnd = 'transitionend webkitTransitionEnd oTransitionEnd otransitionend'; /*Shorthand Ref*/
var stgs=[]; var stgix=0; var totix=0; var aniloc=0; currcl=''; /*Initiate*/
function animastage() {stgix=totix%mxstgs; totix++; var nucls=stgs[stgix];
$('#elemidX').removeClass(currcl).addClass(nucls).one(transEnd, function() {
currcl=nucls; if(aniloc>0) {return;} /*External Stop Animation*/
/*Can do things here based on stgix or totix :synchronise other ellements etc*/
setTimeout('animastage()',30); }); }
$( document ).ready(function() {
stgs=$('#elemidX').attr('class').split(/\s/); stgs.shift(); mxstgs=stgs.length; currcl=stgs[mxstgs-1];
var cls=stgs.join(' '); $('#elemidX').removeClass(cls).addClass(currcl); /*retained classes .eleorg and .stg0*/ });
Regards

Show hide div with animation

I made this script, which opens a div with the right class and close the others.
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hideable");
for (var i = 0; i < divs.length; i = i + 1) {
divs[i].style.display = "none";
}
divid.style.display = "block";
}
return false;
}
Is it possible to make some animation, like fadout, easeout instead of just showing it by display options?
You could try this
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
var divs = document.getElementsByClassName("hideable");
for (var i = 0; i < divs.length; i = i + 1) {
$(divs[i]).fadeOut("slow");
}
$(divid).fadeIn("slow");
}
return false;
}
Have a look at this fiddle "http://jsfiddle.net/9jtd3/"
There are many more techniques provided by Jquery library, You should have a look at that too.
You can use slideDown() and slidUp() of jQuery
$( document.body ).click(function () {
if ( $( "div:first" ).is( ":hidden" ) ) {
$( "div" ).slideDown( "slow" );
} else {
$( "div" ).slideUp("slow");
}
});
This example will toggle multiple elements with the same class name. This example does not need jquery.
HTML:
<button onclick="fadeInAndOut(this)" style="width:100%">Toggle 1</button>
<div class="accordianPanel acordianPanelHidden accordianPanelStyle">Panel 1</div>
<button onclick="fadeInAndOut(this)" style="width:100%">Toggle 2</button>
<div class="accordianPanel acordianPanelHidden accordianPanelStyle">Panel 2</div>
Javascript:
function fadeInAndOut(thz) {
var elmt = thz.nextElementSibling;//Get the element that is below the button that
//was just clicked
elmt.classList.toggle("acordianPanelHidden");//Toggle the class which changes
//attributes which triggers the `transition` CSS
}
CSS
.accordianPanel {
opacity: 1;
height:100%;
transition: all 1s;
}
.accordianPanel.acordianPanelHidden {
opacity: 0;
height: 0px;
visibility:hidden;/* This must be used or some strange things happen -
What happens is that even though the content of the panel is not shown
any buttons in the content can still be clicked -
So basically there are invisible buttons that can accidently get clicked -
if the visibility is not set to hidden - And the visibility doesn't need to be explicitly changed to visible
from hidden in order to show the content
because if visibility:hidden is not used then by default the content is
displayed -
*/
}
.acordianPanelShown {
height: 100%;
width: 100%;
opacity: 1;
}
.accordianPanelStyle {
background:red;
}
This will surely solve your problem.
You can use .fadeOut() directly if you have included jQuery library in your script.
This is way easier with only CSS.
You make a class
div {
display:block;
transition: all .2s ease-out;
}
.hidden {
display:none;
}
And with javascript, you apply or remove the class hidden when you want to. jQuery animation lib is wayyyy far from good to be used. It's clunky, and ressource eating for your user. CSS works with your GPU instead, allowing a more fluid animation.
If You are using Jquery then another way to do this is
function showhide(id) {
$(".hideable").fadeOut("slow");
$("#" + id).fadeIn("slow");
}
Assuming "hideable" as className in your group of divs
Good luck.
You can do that using a Library like jQuery or something.
You can sure make it using plain javascript, but there's no point doing that since jQuery is an amazing library.
See some examples of show and hide

Categories