Animate and then replace the class of div with fade effect - javascript

JSFiddle: Fiddle
The way it is supposed to work is as follows:
1 - the red blocks slide from top to bottom
2 - once that is done then the red boxes fadeOut
3 - then blue boxes fadeIn
Following is the html :
<div class="posRel">
<div class="trans1"></div>
<div class="trans2"></div>
<div class="trans3"></div>
<div class="trans4"></div>
<div class="trans5"></div>
<div class="trans6"></div>
<div class="trans7"></div>
</div>
Following is the js :
for (i = 1; i <= 7; i++) {
$('.trans' + i).toggleClass('toggle');
}
setTimeout(function () {
$('.toggle').fadeOut('slow', function () {
$(this).addClass('fSmall1').fadeIn('slow');
});
}, 2000);
Link to the project: http://50.87.144.37/~projtest/team/design/EO/page-2.html
Link to the JSFiddle
Issues that i am facing :
fadeOut and fadeIn are not working
anything better than settimeout to do this?
I am rather inexperienced when it comes to js/jQuery so feel free to point out any silly mistake(s) too. Thanks.

i had used fadeto property, try the link. http://jsfiddle.net/zcYLM/10/
[http://jsfiddle.net/zcYLM/10/][1]
[1]: http://jsfiddle.net/zcYLM/10/

If you're using jQueryUI, this will work:
http://jsfiddle.net/zcYLM/11/ (this is an updated one)
This is a basic, stripped down example of your problem, but you can apply it to your code.
JS:
$(document).ready(function() {
$('div[class*=trans]')
.toggleClass('toggle', 2000)
.promise()
.done(function() {
$(this)
.fadeOut(2000)
.promise()
.done(function() {
$(this)
.addClass('blue')
.fadeIn(2000);
});
});
});
CSS:
.posRel {
position:relative;
}
div.posRel > div {
background-color:red;
position:absolute;
top:0px;
width:100px;
height:100px;
}
div.posRel > div.trans1 { left:-50px; }
div.posRel > div.trans1.toggle { left:100px; top:150px; }
div.posRel > div.blue { background-color:blue; }

I'll try and attack most of your problems in one hit, but I suspect we may need a little back and forth to completely solve it.
Firstly, your fade in / out issue is tied to the way your animation is being fired. You're essentially calling the fade out on every element individually and then the fade in, but from the functionality you described in your requirements you should be firing one fade on the container instead:
for (i = 1; i <= 7; i++) {
$('.trans' + i).toggleClass('toggle');
}
setTimeout(function () {
$('.posRel').fadeOut('slow', function () {
$('.toggle').addClass('fSmall1');
$('.posRel').fadeIn('slow');
});
}, 2000);
Fiddle
Smooth Transition
If you'd like to have a smooth fade without it blinking out and then back in you can use the fadeTo() method instead. A FadeTo() example can be found below, this will have all of the shapes fall down, pause for a fraction of a second, and then change colour. You can experiment with removing the setTimeout now that the fadeTo controls the animation time, but I've left it as close to the original as possible.
for (i = 1; i <= 7; i++) {
$('.trans' + i).toggleClass('toggle');
}
setTimeout(function () {
$('.posRel').fadeTo('slow', 2, function () {$('.toggle').addClass('fSmall1');});
}, 2000);
fadeTo() Example Fiddle

Related

Vanilla javascript, not CSS or jQuery, fade in, fade out image change

I know this is fairly easy in jQuery, but I want to do this in plain 'ol "will be around forever" javascript.
I have a dropdown select on my page. I choose one of 8 options. There is a default image showing on the page. When I select an option, the image changes to that pic. It all works fine.
But I want to make the image change a fade out, fade in switch over because I, like most of you, can't leave well alone. We have to keep fiddling.
The javascript that I have, which is triggered by an onchange="setPicture()" on the select dropdown is:
function setPicture(){
var img = document.getElementById("mySelectTag");
var value = img.options[img.selectedIndex].value;
document.getElementById("myImageDiv").src = value;
}
This works fine. The value of the selected index is a string with the path for each image. I just want a fade out then fade in stuck in there somewhere. I have fiddled about a bit, calling another function before changing the src but no luck.
Can someone point me in the right direction?
The easier way would be to use css keyframes alone.
But from javascript there is the web animation api made for that.
Here is a quick modif from the example, to match your case.
function setPicture(){
alice.animate(
[
{ opacity: 1 },
{ opacity: .1},
{ opacity: 1 }
], {
duration: 3000,
iterations: Infinity
}
)
}
<button onclick="setPicture()">
OPACITY ANIMATION
</button>
<img id="alice"
src="https://mdn.mozillademos.org/files/13843/tumbling-alice_optimized.gif"
>
</img>
How about setting the image default CSS with the opacity of 0 and with transition time
then in JavaScript just add a class that will make the opacity set to 1
HTML:
<img class="img1" src="sampleimg.jpg">
CSS:
.img1 {
opacity: 0;
transition: all .3s;
}
.img1.show {
opacity: 1;
}
JS:
function setPicture() {
var img = document.querySelector('.img1');
img.src = 'urlofnewimage';
img.classList.add('show');
}
Hope this helps.
Juste one function for all :
function fadeOutEffect(target) {
var fadeTarget = document.getElementById(target);
fadeTarget.style.opacity = 1;
fadeTarget.style.transition = "opacity 2s";
fadeTarget.style.opacity = 0;
setTimeout(function(){
fadeTarget.style.display = "none";
}, 2000);;
}

Prevent jQuery from jumping to the bottom (when using fadeIn)

I've created some divs fading in with jQuery, I have a problem if the user scrolls a bit down though. If you are not at the top of the page, it will always jump to the bottom when a new div fades in.
Here's my code:
<style>
#overflowwrap {
overflow:hidden !important;
}
</style>
<div id="overflowwrap">
<div id="five" style="display: none;">a lot of content</div>
<div id="four" style="display: none;">a lot of content</div>
<div id="three" style="display: none;">a lot of content</div>
<div id="two" style="display: none;">a lot of content</div>
<div id="one" style="display: none;">a lot of content</div>
</div>
<script>
$('#overflowwrap').css('max-height',$(window).height());
$("#one").fadeIn(500);
setTimeout( function show() {
$("#two").fadeIn(500);
}, 3000);
setTimeout( function show() {
$("#three").fadeIn(500);
}, 6000);
setTimeout( function show() {
$("#four").fadeIn(500);
}, 9000);
setTimeout( function show() {
$("#five").fadeIn(500);
}, 12000);
</script>
Update: Example fiddle: https://jsfiddle.net/6qj1hbp0/1/
This wouldn't be a problem, if this was the only element on a page and the user couldn't scroll. However, it's integrated on another site (survey software), so the user is able to scroll.
Is there anything I can do to prevent the site from jumping to the bottom?
Try a different approach.
Instead, of display: none on every element, try opacity: 0;
Then instead of:
setTimeout( function show() {
$("#two").fadeIn(500);
}, 5000);
use:
setTimeout( function show() {
$("#two").addClass('is-visible);
}, 5000);
and add:
.is-visible { opacity: 1 !important; }
within your <style> tags.
you cannot “freeze” scroll, but you can read and change the scroll position, especially because you are using jQuery.
My solution consists in saving the current position of the scroll immediately before the fadeIn instruction then reassign the same value immediately after, with this function:
function fadeInElement(id, time) {
var currentScroll = $(window).scrollTop();
$('#' + id).fadeIn(time);
$(window).scrollTop(currentScroll);
}
Then you may call the same function several times with different ids and duration time, something like this:
fadeInElement('one', 500);
or this:
setTimeout(function() {
fadeInElement('two', 500);
}, 5000);
You may look a working example on CodePen or on JSFiddle
In short, the easiest thing you can do is hide the previous div every time you show a new one.
https://jsfiddle.net/6qj1hbp0/2/
$("#one").fadeIn(500);
setTimeout( function() {
$("#one").hide();
$("#two").fadeIn(500);
}, 3000);
setTimeout( function() {
$("#two").hide();
$("#three").fadeIn(500);
}, 6000);
setTimeout( function() {
$("#three").hide();
$("#four").fadeIn(500);
}, 9000);
setTimeout( function() {
$("#four").hide();
$("#five").fadeIn(500);
}, 12000);
If you want to fade from one box to the other (which creates a much smoother looking effect), you will need to do some other stuff - most notably:
put the boxes in order, top to bottom, #one to #five (you should do this anyways - it just makes sense congnatively)
set the position to absolute for each of the boxes
set some other styles (see the fiddle below)
use a special class while a box is fading in
https://jsfiddle.net/6qj1hbp0/3/
It's simple. Just reorder your div's to the order you want to show them instead of "five, four, three, two, one".
Your browser doesn't have any intention to take you to the bottom, it's just trying to keep your view point fixed on the current hash navigation. As your fading div is always above, your scrollTop will just jump to the bottom.
Another solution - if you don't want to reorder - is to remove all div id's and creating other way to recognize them, something like "data-id".
PS: look for some id's after too!
Do you need to restrict the overflow with hidden?
You can just set overflow: auto and browser will automatically take care of ensuring scrollTop remains the same after the fade in. The element user is looking at after scroll will remain at the same offset. If user hasn't scrolled then it will show the latest faded element at the top
Here's a jsfiddle: https://jsfiddle.net/sm2qaa3c/2/
After re-reading your comment, it seems you always want to display the latest faded div at the top. In that case you want a function to reset scrollTop to 0. You want to do it on overflowwrap not window since that's where the overflow scrolling will happen.
['#one', '#two', '#three', '#four', '#five'].forEach((id, idx) => {
setTimeout(() => {
$(id).fadeIn(500);
$('#overflowwrap').scrollTop(0);
}, idx * 5000);
});
See jsfiddle: https://jsfiddle.net/sm2qaa3c/3/
Thanks for the answers, they didn't work for my purpose though.
However, I've got a solution from another forum which doesn't require changing the functionality. This seems to work:
$('#overflowwrap').css('max-height', $(window).height());
fadeIn("#one", 0)
fadeIn("#two", 5000)
fadeIn("#three", 10000)
fadeIn("#four", 15000)
fadeIn("#five", 20000)
function cs() {
console.log(document.scrollingElement.scrollTop)
}
document.scrollingElement.scrollTop = 16
function fadeIn(el, when) {
setTimeout(function show() {
var t=document.scrollingElement.scrollTop
$(el).fadeIn(500);
document.scrollingElement.scrollTop = t
}, when);
}
Here is a working example on JSFiddle: https://jsfiddle.net/6qj1hbp0/4/

How to show divs when the mouse moves anywhere on screen, not just the element itself?

I managed to hide and show my classes when the user moves his mouse over the specific element. But what I would actually like is that these show when the user moves his mouse anywhere on the screen, not just the selected div's.
This is my current code:
$(window).on('mousemove', function () {
$('.barhide').addClass('show');
try {
clearTimeout(timer);
} catch (e) {}
timer = setTimeout(function () {
$('.barhide').removeClass('show');
}, 1000);
});
And my css:
.barhide {
background: #333;
color: #fff;
display: block;
opacity: 0;
transition: all 1.5s ease;
}
.barhide.show {
opacity: 1;
display: none;
}
So what I would like is that after 3 seconds, the classes with .barhide get hidden and if the user moves his mouse anywhere in screen, they show up again, instead of just when they move over the element.
Also I was wondering if it's not a lot easier to do these things with React?
I have restructured the code a bit and added some comments explaining what's happening and when. Also, lose the try since attempting to clear a timer will never throw an exception.
Keep in mind that mouseover type events are an issue on mobile devices. These two articles may help in that regard:
JQuery's Virtual Mouse Events
Simulated Mouse Events using JQuery
$(function(){
// When page loads, wait 3 seconds and hide all elements with .barhide class:
setTimeout(toggle, 3000);
});
var timer = null;
// General function for adding/removing the "hide" class.
// This is used when the page first loads and each time
// the mouse moves on the page. We're not calling toggle()
// here because a flicker effect can happen which would leave
// the elements showing instead of being hidden.
function toggle(){
$('.barhide').toggleClass('hide');
}
$(window).on('mousemove', function(){
// When anywhere on page is moused over bring back .barhide
// elements for 3 seconds. Removing "hide" simply restores
// the original CSS & layout
$('.barhide').removeClass('hide');
// Kill any previous timers
clearTimeout(timer);
// Wait 3 seconds and hide again
timer = setTimeout(toggle, 3000)
});
.barhide { background-color:blue; }
.hide { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="barhide">ONE</div>
<div class="show">TWO</div>
You just count the nr of timers running and when the last finishes you hide the bar.
var count = 0;
$(window).mousemove(function( event ) {
$('.barhide').show();
count += 1;
setTimeout(function() {
if (count == 1) {
$('.barhide').hide();
}
count -= 1;
}, 3000);
});

Javascript hide and show a div in a loop for a text "blink" effect

I recently wanted to make a element in a div with the ID of "test" to have a "blink" effect like most text editors have where the cursor is hidden and then shown, then hidden and shown....(in a loop) I tried to recreate this effect but just couldn't get it to work. Please help!
Here is some code:
<div id="test">
<p> _ </p>
</div>
Something like this?
setInterval(function(){
$("#test p").toggle();
},3000);
blinks every 3 seconds.
Here's a concise, pure JavaScript way.
blink = setInterval(function () {
element = document.querySelector("#test p");
element.style.opacity = (element.style.opacity == 1 ? 0 : 1);
}, 500);
If you want to stop it, run clearInterval(blink).
Here's a working fiddle.
FIDDLE
setInterval(function(){
$("#test p").toggle();
},300);
Here is an example using Javascript
setInterval(function(){
var elem = document.querySelector("#test p");
if(isVisible(elem)) {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
},500);
function isVisible(elem) {
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
}
(Though knouroozi's answer will stop the contents from shifting around, so I'd suggest that.)
With JQuery it becomes simpler:
setInterval(function(){
$('#test p').toggle();
},500);
(stckrboy's answer covers toggling visibility, rather than 'display', which will prevent the content from shifting around.)
Here's an example using jQuery and setInterval
$(".crsr").each(function(){
var elem=$(this);
setInterval( function() {
if(elem.css('visibility')=='hidden') {
elem.css('visibility','visible')
} else {
elem.css('visibility','hidden')
}
},500)
});
jSFiddle
Throwing my approach into the ring. :) Set up a class that changes the visibility to hidden and then use setInterval and toggleClass to toggle the class off and on.
HTML
<div id="blinkingText">
Blink for me!
</div>
CSS
<style>
.blinkOn {visibility: hidden;}
</style>
JS
<script type="text/javascript">
$(document).ready(function(){
setInterval(function() {
$("#blinkingText").toggleClass("blinkOn");
},1000);
});
</script>

Javascript - fading from one item to another pops up with both briefly

I have a testimonials area on my website that fades from one testimonial to another. I'm having an issue where it will fade out too slowly before the next item fades in causing both to come up making a large div making it look ugly.
I want it to fade from one testimonial to another without jumping and flashing with both.
You can see an example here: http://ledragonvert.com/index_test.php
Here is my Javascript code:
function rotate_p() {
if (p_current == p_count) {
p_current = 1;
} else {
p_current++;
}
var $container = $('#container');
$container.find('p').fadeOut();
$container.find('p:nth-child(' + p_current + ')').fadeIn();
}
var p_count;
var p_current = 0;
var p_interval;
$(document).ready(function () {
rotate_p();
p_count = $('#container').find('p').length;
p_interval = setInterval(function () {rotate_p();}, 7000);
});
Thanks you very much for taking your time out to help me.
the solution is CSS based. since the position of the "p" element is static and you call both fadeOut and fadeIn, there is an overlap, as two p elements are inevitably shown together. To get them one on top of the other you need to use absolute positioning on the p element, like so:
#container {
position:relative;
}
#container>p {
position:absolute;
//use any values you wish, to set the testimonial relative to #container:
top:10px;
left:50px;
}

Categories

Resources