Hello I'm trying to make typewriter with fadeIn effect but my method doesn't work. Could you tell me how can I add fadeIn effect to this script?
<div class="inner container">
<h2>Typewriter test</h2>
</div>
var title = $('.inner h2').html();
$('.inner h2').html('');
var arrayTitle = title.split('');
var i = 0;
var interval = setInterval(function () {
if (i > arrayTitle.length) {
$('.inner h2').html(title);
clearInterval(interval);
} else {
//$('arrayTitle[i]').hide().appendTo('.inner h2').fadeIn();
$('.inner h2').append(arrayTitle[i]).fadeIn(50);
i++;
}
}, 50);
You can't fadeIn individual characters like that - your fadeIn() call is applied to the whole header, which is already visible. If you add each character as a <span>, you can fade that in:
var header = $('.inner h2');
var title = header.text();
header.text('');
var arrayTitle = title.split('');
var i = 0;
var interval = setInterval(function(){
if (i > arrayTitle.length)
{
header.text(title); // wipe out the <span> tags
clearInterval(interval);
}
else
{
$('<span>')
.text(arrayTitle[i])
.appendTo(header)
.hide()
.fadeIn(50);
i++;
}
}, 50);
Example, with longer intervals to show the fade-in more clearly: http://codepen.io/paulroub/pen/ixBdm
Related
So I have an h1 ("Hello, I'm xxxxxxxxx") and wraped "Hello" in span with "greeting" id and I change the text in js every 3s to an Hello in another language. It works fine but I want it change smoothly but not pop up suddenly.
// change text every 3 second
var text = ["Hola", "Hallo", "Merhaba"];
var counter = 0;
var elem = document.getElementById("greeting");
setInterval(change, 3000);
function change() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}
With Jquery, you might want to use fadeOut(), then fadeIn() functions.
And your code would be like:
var text = ["Hola", "Hallo", "Merhaba"];
var counter = 0;
var elem = $("#greeting");
setInterval(change, 3000);
function change() {
elem.fadeOut(function(){
elem.html(text[counter]);
counter++;
if(counter >= text.length) { counter = 0; }
elem.fadeIn();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='greeting'>Hello<div>
You could do it just by adding some css and using the transition property.
var greet = new Array("Hola", "Hallo", "Merhaba");
var counter= 0;
document.getElementById('greeting').innerHTML = greet[counter];
Changegreeting1();
function Changegreeting1(){
incrementIndex()
document.getElementById('greeting1').innerHTML = greet[counter];
document.getElementById('greeting').style.opacity = 0;
document.getElementById('greeting1').style.opacity = 1;
setTimeout(Changegreeting, 2000);
}
function Changegreeting(){
incrementIndex();
document.getElementById('greeting').innerHTML = greet[counter];
document.getElementById('greeting').style.opacity = 1;
document.getElementById('greeting1').style.opacity = 0;
setTimeout(Changegreeting1, 2000);
}
function incrementIndex(){
if(counter < greet.length - 1 ){
counter++;
}else{
counter = 0;
}
}
#greeting{
transition: opacity 1s;
}
#greeting1{
transition: opacity 1s;
position:absolute;
top:0px;
margin-top:0px
}
<p id = "greeting"></p>
<p id = "greeting1"></p>
Is that what you want
If by "change smoothly" you mean some smooth transition, as in fade out and fade in, I would suggest looking at jQuery fadeOut and fadeIn methods.
The change() function with animation duration set to 100 could look something like this:
function change() {
// Fade out
$("#greeting").fadeOut(100, function() {
// Increment the counter
counter++;
if(counter >= text.length) { counter = 0; }
// Update the text and fade in
$("#greeting").text(text[counter]).fadeIn(100);
})
}
Currently, this code is auto fade in and fade out div by selecting the div element the way they were arranged (consecutive order). What I want to do now is to make the selector in random, I want to fade in a random div and after fading it out it will pick another random div and infinite loop the process. Since I'm new in jQuery and so confused, I also want to know your opinion on how to put this such process on a If Else statement in the easiest way. Like for example, I will get the value of a number
int num = 1;
If(num == 1){
<!-- Do the process-->
}
Else {
<!-- Do another process by selecting from another set of divs-->
}
Here is the code:
jQuery.fn.nextOrFirst = function (selector) {
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
}
$(document).ready(function () {
$('div.mb').fadeOut(500);
var fadeInTime = 1000;
var intervaltime = 3000;
setTimeout(function () {
fadeMe($('div.mb').first());
}, intervaltime);
function fadeMe(div) {
div.fadeIn(fadeInTime, function () {
div.fadeOut(fadeInTime);
setTimeout(function () {
fadeMe(div.nextOrFirst());
}, intervaltime);
});
}
});
Divs:
<div class="boxes">
<div class="mb one">1-------------one</div>
<div class="mb two">2-------------two</div>
<div class="mb three">3-------------three</div>
</div>
Not sure if this is exactly what you want but can be modified:
var mb = $('.mb'),
mbl = mb.length;
mb.hide();
rand();
function rand(){
var r = getRand(0, mbl);
mb.eq(r).fadeIn('slow', function(){
$(this).fadeOut('slow', function(){
setTimeout(rand, 200);
});
});
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
Try changing the nextOrFirst function to something like:
jQuery.fn.nextOrFirst = function (selector) {
var xCount = selector.size();
return Math.floor(Math.random() * xCount ) + 1;
}
Instead of getting the next of first div, this gets a count of all of the divs,
and pics a random number between 1 and X(the number of divs with your selector)
Try something like this,Hope it helps
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").fadeIn();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").fadeOut(1000);
}, 3000);
EDIT:
var c=$(".boxes div");
setInterval(function(){
$.each(c,function(a,z){
$("div[class='"+(z.className)+"'").hide();
});
var item = c[Math.floor(Math.random()*c.length)];
var u=item.className;
$("."+u).fadeOut();
$("div[class='"+u+"'").show().fadeIn(1000);
}, 2000);
FIDDLE LINK: https://jsfiddle.net/bv0jj4wp/29/
How do you add a Fade in and Fade out effect to a text slide using jquery
I would like to have each quote fade in and out versus just disappear and reappearing sluggishly.
<head>
<script>
var counter = 0;
function changeText()
{
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
if (counter > 4)
{
counter = 0;
}
document.getElementById("textslide").innerHTML = quotes[counter];
setTimeout(function(){changeText()},10000);
counter ++;
}
</script>
</head>
<body onload="changeText();">
<p id="textslide"></p>
</body>
You can use Jquery's fadein() and fadeout() effectively like
$( "#DivID" ).fadeIn( "slow", function() {
// After Animation complete
});
Would it be possible to do this:
http://jsfiddle.net/arunpjohny/asTBL/
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
But with the DIVs crossfading directly into each other rather than first fading to white and then fading from white?
Also, would it be possible to stop the animation on hover (and resume it when not hovering)?
I searched for several solutions but couldn't find a way to do it (I'm a noob with javascript). CSS solutions didn't match my needs because they wouldn't work correctly with DIVs having links inside it...
Thank you so much in advance.
To make your divs fade at the same time you will need to add a bit of styling (to make the quotes sit on top of each other) and run the fades simultaneously. Then you will need to clear the timeout on hover to pause the animation:
jQuery(function () {
var $els = $('div.quote'),
i = 0,
len = $els.length;
$els.slice(1).hide();
var fadeInterval = setFadeInterval(); // starts the fader
$els.hover(function () {
clearInterval(fadeInterval); // stops the fader on mouseover
},
function () {
fadeInterval = setFadeInterval(); // restarts the fader on mouseout
});
function setFadeInterval() {
return setInterval(function () {
$els.eq(i).fadeOut(); // run the faders at the same time
i = (i + 1) % len
$els.eq(i).fadeIn();
}, 2500);
}
});
/* make the faders sit on top of each other */
#quote-holder {
position:relative;
}
#quote-holder > .quote {
position:absolute;
top:0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="quote-holder">
<div id="quote1" class="quote"> <span class="quote">I am a quote</span>
<span class="author">Author Name</span>
</div>
<div id="quote2" class="quote">I am another quote</div>
<div id="quote3" class="quote">I am yet another quote</div>
</div>
JSFIDDLE
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
var timer = setInterval(animation, 2500)
function animation(){
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}
$('#content').hover(function (){
clearInterval(timer);
},function (){
setInterval(animation,2500);
})
})
I restructure your code and create a animation function to achieve.
I am using this script to hide and show text however, I want to make the transition smoother but I am not sure how to. Here's a demo of it: http://jsfiddle.net/LnE5U/.
Please help me change it to make it smoother.
hide/show text
<div id="showOrHideDiv" style="display: none">hidden text</div>
<script language="javascript">
function showOrHide()
{
var div = document.getElementById("showOrHideDiv");
if (div.style.display == "block")
{
div.style.display = "none";
}
else
{
div.style.display = "block";
}
}
</script>
Here is an example using jQuery's fadeToggle (a shortcut for a more complicated animate)
// assuming jQuery
$(function () { // on document ready
var div = $('#showOrHideDiv'); // cache <div>
$('#action').click(function () { // on click on the `<a>`
div.fadeToggle(1000); // toggle div visibility over 1 second
});
});
HTML
<a id="action" href="#">hide/show text</a>
<div id="showOrHideDiv" style="display: none;">hidden text</div>
DEMO
An example of a pure JavaScript fader. It looks complicated because I wrote it to support changing direction and duration mid-fade. I'm sure there are still improvements that could be made to it, though.
function generateFader(elem) {
var t = null, goal, current = 0, inProgress = 0;
if (!elem || elem.nodeType !== 1) throw new TypeError('Expecting input of Element');
function visible(e) {
var s = window.getComputedStyle(e);
return +!(s.display === 'none' || s.opacity === '0');
}
function fader(duration) {
var step, aStep, fn, thisID = ++current, vis = visible(elem);
window.clearTimeout(t);
if (inProgress) goal = 1 - goal; // reverse direction if there is one running
else goal = 1 - vis; // else decide direction
if (goal) { // make sure visibility settings correct if hidden
if (!vis) elem.style.opacity = '0';
elem.style.display = 'block';
}
step = goal - +window.getComputedStyle(elem).opacity;
step = 20 * step / duration; // calculate how much to change by every 20ms
if (step >= 0) { // prevent rounding issues
if (step < 0.0001) step = 0.0001;
} else if (step > -0.0001) step = -0.0001;
aStep = Math.abs(step); // cache
fn = function () {
// console.log(step, goal, thisID, current); // debug here
var o = +window.getComputedStyle(elem).opacity;
if (thisID !== current) return;
if (Math.abs(goal - o) < aStep) { // finished
elem.style.opacity = goal;
if (!goal) elem.style.display = 'none';
inProgress = 0;
return;
}
elem.style.opacity = (o + step).toFixed(5);
t = window.setTimeout(fn, 20);
}
inProgress = 1; // mark started
fn(); // start
}
return fader;
}
And using it
window.addEventListener( // this section matches the code above
'load',
function () {
var fader = generateFader(document.getElementById('showOrHideDiv'));
document.getElementById('action').addEventListener(
'click',
function () {
fader(1000);
}
);
}
);
DEMO of this
This is quite simple. I have just made a demo and i used setInterval
Here's how it works
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
}
}, 50);
};
JSFiddle Demo Link
Steps
Create a function that accepts a DOM element
Set the opacity of the element to 1
Create a function that loops every 50ms
If the opacity is greater than 0 -> continue
Take away 0.01 from the opacity
if it's less than 0 the animation is complete and hide it completely
Note this is a really simple example and will need a bit of work
You can use somthing like this
$('.showOrHideDiv').toggle(function() {
$('showOrHideDiv').fadeIn('slow', function() {
//fadeIn or fadeOut, slow or fast, all the stuffs you want to trigger, "a function to execute every odd time the element is clicked," says the [jquery doc][1]
});
}, function() {
//here comes "additional handlers to cycle through after clicks," says the [jquery doc][1]
});
I used OPACITY to make it show/hide. See this Example, Full code (without jQuery):
Click here
<div id="MyMesage" style="display:none; background-color:pink; margin:0 0 0 100px;width:200px;">
blablabla
</div>
<script>
function ShowDiv(name){
//duration of transition (1000 miliseconds equals 1 second)
var duration = 1000;
// how many times should it should be changed in delay duration
var AmountOfActions=100;
var diiv= document.getElementById(name);
diiv.style.opacity = '0'; diiv.style.display = 'block'; var counte=0;
setInterval(function(){counte ++;
if ( counte<AmountOfActions) { diiv.style.opacity = counte/AmountOfActions;}
},
duration / AmountOfActions);
}
</script>
I followed iConnor solution and works fine but it had a small issue setInterval will not stop after the element be hidden I added stop interval to make it better performance
var fadeout = function( element ) { // 1
element.style.opacity = 1; // 2
let hidden_process = window.setInterval(function() { // 3
if(element.style.opacity > 0) { // 4
element.style.opacity = parseFloat(element.style.opacity - 0.01).toFixed(2); // 5
} else {
element.style.display = 'none'; // 6
console.log('1');
clearInterval(hidden_process);
}
}, 50);
};