JavaScript: addClass when element is in viewport using animate.css - javascript

I am using animate.css which is nice and simple as I am a beginner. I can get the animation to work and can delay the animation with animation-duration: 3s and animation-delay: 0s; But I can't find how to trigger it when it comes into my viewport as I scroll down to it. Here is the code I have tried so far:
HTML
<div class="about-container">
<p>Content here...</p>
</div>
CSS
.about-container{
background-color: #a3c17f;
width: 500px;
height:500px;
margin: 0 auto;
}
JAVASCRIPT
$(function() {
if ($("#about-container").length > 0) {
addClass('animated pulse')
}
});
</script>

Look at your element. You are using class. So it should be $('.about-container'). However you can change it into ID.
$(function() {
if($('#about-container').length > 0) { // check if there's an element
$('#about-container').addClass('animated pulse'); // this is how you add class in jquery
}
});
Plain Javascript
var abtContainer = document.getElementById('about-container');
if(abtContainer.length > 0) {
abtContainer.classList.add('animated pulse');
}
However this method don't work on IE8 and below.
So you need to use this if you are supporting old browsers.
abtContainer.className += ' animated pulse';
http://codepen.io/anon/pen/QERZpz

Try this:
"OnScreen JS"
A jQuery plugin that does stuff to elements when they enter or leave the viewport
https://silvestreh.github.io/onScreen/

function addClass(elem, clazz) {
if (!elemHasClass(elem, clazz)) {
elem.className += " " + clazz;
}
}
function elemHasClass(elem, clazz) {
return new RegExp("( |^)" + clazz + "( |$)").test(elem.className);
}
try this
jQuery('.row.homeCats').addClass("hideme").viewportChecker({
classToAdd: 'visible animated fadeInDown',
});

From your code, it seem you are adding addClass('animated pulse').
Since addClass supports multiple class your code is right.
For testing your code you can try applying class like this manner .addClass('animated ').addClass('pulse');
But use $(this).addClass('animated pulse') in order to append class to '.about-container' DIV.
From your given HTML DIV you dont have ID #about-container,
So replace ,
$(function() {
if ($(".about-container").length > 0) {
$(this).addClass('animated pulse'); // Add class supports multiple class
//OR
$(this).addClass('animated'). addClass('animated'); // But try this also
}
});

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.

How to add transition into Javascript document.getElementById("myDIV").style.display = "none";

How can I add transition to document.getElementById("myDIV").style.display = "none"; I am currently working on a registration form in which if one input is of a certain value the other div is hidden but it looks so rough, Is there a way to add transitions into the following JS ?
<script type="text/javascript">
function myFunction() {
document.getElementById("myDIV").style.display = "none";
}
function hideshow(which){
if (!document.getElementById)
return
if (which.style.display=="block")
which.style.display="block"
else
which.style.display="block"
}
function myFunction1() {
document.getElementById("myDIV2").style.display = "none";
}
</script>
Create functions with parameters like
function hideDiv(div_id) {
document.getElementById(div_id).style.display = "none";
}
function showDiv(div_id) {
document.getElementById(div_id).style.display = "block";
}
The way to make a nice transition is to set style.display= "none" after you perform some kind of animation that removes the element from view.
You could:
Fade it out (set opacity to 0 - fade it with transition in CSS)
Slide it up/down/left/right (animation library or fancy CSS)
Do some other fancier animation (like bounce, shrink etc.)
Then, set style.display = "none"
The easiest way to do this (in my opinion) is with an animation library. I personally recommend VelocityJS because you don't need jQuery to run it.
I don't think there is anyway to do that with simple js, however I did it easily using JQuery
<script type="text/javascript">
$(document).ready(function(){
$("#myDIV").show();
$(document).on('click', '.married' , function() {
if (this.value == "never_married"){
$("#myDIV").hide('slow');
} else {
$("#myDIV").show('slow');
}
})
});
The reason is display isn't animated, setting it from block to none won't give you the result you're looking for.
A nice way to do this is to use CSS alongside JavaScript for the transition.
Add Transition to your myDIV style such as:
#myDIV {
opacity: 1;
transition: 1s ease;
}
#myDIV.hidden {
opacity: 0;
transition: 1s ease;
}
Then with JavaScript apply the hidden class to #myDiv and you'll get your animation.
Once the animation has finished then set el.style.display = 'none'; to make it disappear completely from view.

Using prototype with scrollTop to make instances of a Class(js class) active (css class)

I think the title is pretty confused, but i dont know how to named what i'm trying to do.
I have a paragraph:
<p data-initial="100" data-final="1000">Test</p>
NOTE THE DATA-*
And this paragraph have a simple CSS:
p {
color: black;
margin-top: 500px;
}
p.active {
color: red;
}
And this paragraph is an instance of Animation class:
+ function($) {
var Animation = function(element) {
this.element = $(element);
this.initial = this.element.data('initial');
this.final = this.element.data('final');
if (this.initial > $(this).scrollTop()) {
this.applyAnimation();
}
}
Animation.prototype.applyAnimation = function() {
alert('WORKED!!');
this.element.addClass('active');
}
Animation.prototype.disableAnimation = function() {
this.element.removeClass('active');
}
$(window).on('load', function() {
$('[data-initial]').each(function() {
var animation = $(this);
animation = new Animation(this);
});
});
}(jQuery);
With this code, i'm trying to apply the .active class in the paragraph if the page scroll more them 100, but is not working at all, not happens.
I think maybe it's because I'm trying to 'hear' the scroll inside the prototype , it is not possible? How can I make my instance hear the scroll and apply the class when the page scroll over 100 ??
If i do this:
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
console.log('test');
}
});
The test will appear in my console, so, the window.scroll code is not wrong.
I think this line might cause a problem:
if (this.initial > $(this).scrollTop()) {
"this" will be the new instance of Animation which isn't an element. Maybe that should be this.element.scrollTop()?

Replace image on hover

I'm trying to replace an image with another image.
Since the webpage, that i'm building, has to be viewable in IE8, then CSS based solutions played out quircky.
I tried the
display: none; and display: block; trick
opacity: 0; and opacity: 1; trick
But they both don't function as I want to (centered inside a div, because IE8 plays some stuff differently, then I thought that may-be a simple src="" swaping will do the trick.
I started with jquery, but since I'm pretty bad with understanding the $(this) and DOM, then it isnt working at all, but i think I got my logic right.
So, HTML is here:
<div class="wrapper">
<a href="#">
<img class="original" src="http://placekitten.com/200/200">
<img class="overlay" src="http://placekitten.com/g/200/200">
</a>
…
…
So I have numerous a tags inside a wrapper, each containing two images. As they are responsive and having the same ratio, then no sizes are needed.
And my started jquery:
$('.wrapper a').hover(
function () {
var original = $(this).attr('src');
var overlay = $(this).next().attr('src');
$(this).children('.original').attr('src', overlay);
},
function () {
$(this).children('.original').attr('src', original);
}
);
And here's the JSFiddle .
So, I'm really after this, that each a tag I have inside a wrapper would change the image according to the images inside of that tag.
You don't need javascript here at all. Really. Use CSS:
.wrapper a:hover .original {
display: none;
}
.wrapper a:hover .overlay {
display: inline-block;
}
Demo: http://jsfiddle.net/hHyh6/10/
You should simply show overlay image on hover and hide original image
$('.wrapper a').hover(function () {
$(this).find('.original').toggle();
$(this).find('.overlay').toggle();
}, function () {
$(this).find('.original').toggle();
$(this).find('.overlay').toggle();
});
DEMO
Instead you can try this:
$('.overlay').hide(); //<----------first hide the overlay image
$('.wrapper a').hover(function () {
$(this).find('.overlay').show().add(this).find('.original').hide();
// here find the overlay and show it and hide the original
}, function () {
$(this).find('.overlay').hide().add(this).find('.original').show();
// here find the overlay and hide it and show the original
});
Demo # Fiddle using .end()
Demo # Fiddle using .add(this)
try this js i also tried in your fiddle too it works
var current_cash;
$('.wrapper a').hover(
function () {
current_cash = $(this).find('.original').attr('src');
var overlay = $(this).find('.overlay').attr('src');
$(this).children('.original').attr('src', overlay);
},
function () {
$(this).children('.original').attr('src', current_cash);
}
);

Remove css class with animation

I'm creating a table and i want to highlight a specific row.
I did this using:
$this.css('background-color', 'green');
$this.delay(3000).animate({ backgroundColor: $color }, 3000);
$this = the row in question.
$color = the previous row color.
But i want it to work with the a css class, so something like this
$this.addClass('highlight');
The class .highlight will only have a background-color.
The problems is that, after i add the class, i can't the background-color.
If i use:
$this.delay(3000).animate({ backgroundColor: $color }, 3000);
it doesn't seem to work because it doesn't overrides the background-color property of the class .highlight itself.
And i don't see a way to animate a removeClass method or even a switchClass from .highlight to ''.
Is there any solution i'm not thinking off to do this.
Thanks in advance.
Use CSS transitions instead. Better performance and simpler.
Fiddle example
transition:background-color 0.3s linear;
though this doesn't provide as much browser support for the animation, obviously.
You could use jQuery UI's .switchClass which animates all the style changes: .switchClass
Once completed highlighting, use the callback to switch it back.
$('div').click(function() {
$(this).switchClass( "normal", "color", 1000, "easeInOutQuad", function(){
$(this).delay(3000).switchClass( "color", "normal", 1000, "easeInOutQuad" );
});
});
Fiddle me here!
the .animate() function works with "numeric" properties like: height, width, left, etc.. but not with background-color.
You can try this:
$(document).ready( function() {
$('tr.normal').on('click', function() {
$(this)
.hide()
.delay(3000)
.fadeIn('slow')
.toggleClass('highlight');
});
});
You could use jQuery's addClass and removeClass, consider:
if($(document).scrollTop() > 250)
{
$('#div').addClass("show");
}
else
{
$('#div').removeClass("show");
}
});
What this is doing is replacing the original class, such as "hide" with the div class "show", this particular snippet of code displays a banner when the user scrolls 250px down the page.
Remember if you're using this code that it's still better (and smoother) to use CSS3 transitions UNLESS you're considering users who's browsers don't support this, such as IE8-.
EDIT: I just realized the reason you're doing it this way is because you're considering IE7 users. Perfect. I have literally just solved this issue myself.
The workaround I used was to have a css3 transition set up, and a detector with an if statement to use jQuery where transition isn't supported, see below:
var Detect = (function() {
var
//Add CSS properties to test for
props = "transition".split(","),
//Browser prefixes
CSSprefix = "Webkit,Moz,O,ms,Khtml".split(","),
d = document.createElement("detect"),
test = [],
p, pty;
// test prefixed code
function TestPrefixes(prop) {
var
Uprop = prop.charAt(0).toUpperCase() + prop.substr(1),
All = (prop + ' ' + CSSprefix.join(Uprop + ' ') + Uprop).split(' ');
for (var n = 0, np = All.length; n < np; n++) {
if (d.style[All[n]] === "") return true;
}
return false;
}
for (p in props) {
pty = props[p];
test[pty] = TestPrefixes(pty);
}
return test;
}());
if (Detect.transition) {
$(function(){
$(window).scroll(function() {
//your code here
//remember to use an if else

Categories

Resources