FadeIn div content one by one - javascript

I have some content in div, basically div will be hide, now i want when i press button the div content will be show with fadeIn function, now my problem i want show the div content one by one means one alphabet fadeIn then other but in my case it will be done word by word.
HTML
<div>
<span> THIS IS EXAMPLE OF FADE IN WORLD ONE BY ONE IN ALPHABETIC ORDER</span>
</div>
<input type='button' value='click me'/>
JS
$("input[type=button]").click(function(){
$("div").show();
$("span").each(function(index) {
$(this).delay(400*index).fadeIn(300);
});
});
CSS
div { display:none }
Fiddle Here

The trick is to split your span into smaller spans, one for every letter, and to use setTimeout to fade those spans one after the other :
$("input[type=button]").click(function(){
var $div = $('div');
$div.html($div.text().split('').map(function(l){
return '<span style="display:none;">'+l+'</span>'
}).join('')).show().find('span').each(function(i, e){
setTimeout(function(){ $(e).fadeIn() }, i*100);
});
});
Demonstration

you could also do:
$("input[type=button]").click(function(){
$("div").find("span").hide();
$("div").show();
var spanEle = $("span"),
contentArray = spanEle.text().split(""),
current = 0;
spanEle.text('');
setInterval(function() {
if(current < contentArray.length) {
spanEle.text(spanEle.text() + contentArray[current++]).fadeIn("slow");
}
}, 100);
});
Demo:: jsFiddle

DEMO
$(function () {
$('#test').click(function () {
var dest = $('div span#char');
var c = 0;
var string = dest.text();
dest.text('').parent().show();
var q = jQuery.map(string.split(''), function (letter) {
return $('<span>' + letter + '</span>');
});
var i = setInterval(function () {
q[c].appendTo(dest).hide().fadeIn(1000);
c += 1;
if (c >= q.length) clearInterval(i);
}, 100);
});
});

Demo http://jsfiddle.net/krasimir/4GmSF/1/
HTML
<div>THIS IS EXAMPLE OF FADE IN WORLD ONE BY ONE IN ALPHABETIC ORDER</div>
<input type='button' value='click me'/>
CSS
div {
display: none;
}
div span {
opacity: 0;
}
JavaScript
var transformText = function(selector) {
var div = $(selector);
var words = div.text().split(" ");
var newHTML = '';
for(var i=0; word=words[i]; i++) {
newHTML += '<span>' + word + '</span> ';
}
div.html(newHTML);
}
$("input[type=button]").click(function(){
transformText("div");
$("div").show();
$("div span").each(function(index) {
(function(span, index) {
setTimeout(function() {
span.css("opacity", 0);
span.animate({
opacity: 1
});
}, index*100);
})($(this), index);
});
});

Related

Append div "n" times where "n" is value inside another html div

I have a div that could contain different numbers inside it and a button.
When I click on this button, I want to append divs according to the number in the div, e.g. if I have number 1 then it should append 1 div, if I have number 2 it should append 2 divs, and so on.
I also want *each appended div to have a unique id.
What I have tried so far:
$(document).ready(function() {
$('button').click(function() {
if ($(this).siblings('div').html() == '1') {
$('body').append('<div>' + 'My div' + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
1
</div>
<button type="button">Add</button>
Check the following pure JavaScript approach [jsFiddle] as well as jQuery approach [jsFiddle] to append divs with unique ids based on div value:
Pure JavaScript:
var btn = document.getElementById('btn');
var val = document.getElementById('val').textContent;
var idName = 1;
function addDiv(){
var count = parseInt(val.trim());
for (var i = 0; i < count; i++) {
var appendDiv = document.createElement('div');
appendDiv.setAttribute("class", "newDiv");
appendDiv.setAttribute("id", "someId" + idName);
document.body.appendChild(appendDiv);
idName++;
}
}
btn.addEventListener('click', addDiv);
.newDiv {background-color: red; margin: 5px auto; padding: 10px;}
<div id="val">
4
</div>
<button id="btn" type="button">Add</button>
jQuery:
var idName = 1;
$("button").on("click", function(){
var count = parseInt($("#val").text().trim());
for(let i=0; i < count; i++){
$('body').append('<div class="newDiv" id="newDiv' + idName + '"></div>');
idName++;
}
})
.newDiv {
background-color: red;
margin: 5px auto;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="val">
4
</div>
<button id="btn" type="button">Add</button>
I think something like this could work for you:
<script>
$(document).ready(function() {
$('button').click(function() {
var val = parseInt($(this).siblings('div').text().trim());
for(let i=0; i < val; i++){
$('body').append('<div>'+'TEST'+'</div>');
}
});
});
</script>
You need to remove the white space that precedes or follows the element's content and you do that with .trim().
You also need to be looking at only the previous sibling, not all the siblings because after you add one more div, it won't contain the number that the previous one does and the code will never find a match after that.
Lastly, you should use .text(), not .html() when you are looking at the text content of an element and not its HTML child content.
$(document).ready(function() {
// This is only added to demonstrate that the following
// code works no matter what the number is in the div
let val = prompt("Pick a number");
$("div")[0].textContent = " " + val + " ";
// *****************************************************
let div = $('button').prev(); // Get a reference to the <div> just prior to the button
let num = +div.text().trim(); // Get the text content of that <div> and convert to number
$('button').click(function() {
// Loop the amount of times as was in the <div>
for(var i = 0; i < num; i++) {
// Create a new <div> with an id of the current loop index
$('body').append('<div id=' + i + '>' + 'My div' + '</div>');
}
// Show newly created code (scroll to bottom of results to see)
console.log($("body").html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
</div>
<button type="button">Add</button>

Move cursor to final of input while it is highlithing the text

I need to put the cursor at final of input because it is going at start, it highlights the text so it goes to start.
I tried using this.selectionStart = this.selectionEnd = this.value.length; but it doesn't work pretty well or maybe i am puting it in the wrong line.
Thanks :)
window.setInterval(function() {
change();
}, 1);
function change() {
$(function() {
var elem = $('#code');
highlighter(' new ', elem, "red");
highlighter(' button', elem, "blue");
});
function highlighter(word, elem, color) {
var html = elem.html();
var reg = new RegExp(word, "g");
html = html.replace(reg, "<span class='" + color + "'>" + word + "</span>");
elem.html(html);
}
}
.red {
color: red;
}
.blue {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="code" contenteditable="true">
new button
</div>
var elem = $('#code');
window.setInterval(function(){
change();
}, 1);
function change(){
$(function(){
highlighter(' new ', elem,"red");
highlighter(' button', elem,"blue");
});
function highlighter(word, elem, color){
var html = elem.html();
var reg = new RegExp(word,"g");
html = html.replace(reg, "<span class='"+color+"'>" + word +"</span>");
elem.html(html);
}
function addEvent(elem, event, fn){
if(elem.addEventListener){
elem.addEventListener(event, fn, false);
}else{
elem.attachEvent("on" + event,
function(){ return(fn.call(elem, window.event)); });
}}
addEvent(elem,'focus',function(){
var that = this;
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
Below code should work actually but however because of browser issues looks like not working.
this.selectionStart = this.selectionEnd = this.value.length;
To load this properly I have added time out to get away this
setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

Writing Text Effect with jquery

I am use this code for Writing Text Effect:
<script type="text/javascript">
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
</script>
but its not working for multiline, I use this code:
changeText($("#TypeEffect p, #TypeEffect br"), $(".p2"), 150);
so, its not working.
please help me for Writing Text Effect in multi line.
Try
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var contents = $(cont1).contents().map(function () {
if (this.nodeType == 3) {
if ($.trim(this.nodeValue).length) {
return this.nodeValue.split("")
}
} else {
return $(this).clone().get();
}
}).get();
var i = 0;
function show() {
if (i < contents.length) {
cont2.append(contents[i]);
i = i + 1;
} else {
clearInterval(Otimer)
}
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
Demo: Fiddle
Try this:
$("[class*=autoWrite]").each(function(e){
autoWriteText($(this));
})
function autoWriteText(elm){
var clas = elm.attr("class");
clas = clas.split("-");
var speed = clas[1];
var delay = clas[2];
var txt = elm.html();
elm.html("");
setTimeout(function(){
elm.fadeIn("fast");
txt = txt.split("");
var txtI = 0;
var html = "";
var intrvl = setInterval(function(){
html = html + txt[txtI] ;
elm.html(html + "_");
txtI = txtI + 1;
if(txtI == txt.length){
clearInterval(intrvl);
}
},speed);
},delay)
}
.autoWriteText{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h5 class="autoWrite-10-0" >This element will write a <b>letter every 10 milliseconds</b> in this box, with a <b>delay of 0 milliseconds</b>.</h5>
<hr>
<h5 class="autoWrite-50-1000" >This element will write a <b>letter every 50 milliseconds</b> in this box, with a <b>delay of 1 second</b>.</h5>
<hr>
<h5 class="autoWrite-200-3000" >This element will write a <b>letter every 200 milliseconds</b> in this box, with a <b>delay of 3 second</b>.</h5>
<hr>
<h5 class="autoWrite-500-5000" >This element will write a <b>letter every 500 milliseconds</b> in this box, with a <b>delay of 5 second</b>.</h5>
<hr>

Init an array using contents of spans

I have no Idea how to init my banner array with the text inside my spans. Do you have any Idea? Better to use javascript or JQuery?
<script language="javascript" type="text/javascript">
var i = 1;
function fun() {
var banner = new Array();
//How to init array here from inner text of spans?
i++;
document.getElementById("img1").src = "slide/" + banner[i] + ".jpg";
if (i == 3) //here 2 is number of images i want to display in the slide show
{
i = 0;
}
}
setInterval("fun()", 4000);
</script>
<div class="imagesContainer" style="display:none;">
<span>
73defe4b-9819-4e12-b351-3813686e0c83.gif
</span>
<span>
4c2ed116-500d-42ad-8aa5-983bf214d5d3.png
</span>
</div>
You can use .map()
var i = 1;
function fun() {
var banner = $('.imagesContainer span').map(function () {
return $.trim($(this).text())
}).get();
//How to init array here from inner text of spans?
i++;
document.getElementById("img1").src = "slide/" + banner[i] + ".jpg";
if (i == 3) //here 2 is number of images i want to display in the slide show
{
i = 0;
}
}
setInterval("fun()", 4000);
jQuery(function () {
var i = 0;
var banner = $('.imagesContainer span').map(function () {
return $.trim($(this).text())
}).get();
function fun() {
//How to init array here from inner text of spans?
i++;
if (i == banner.length) {
i = 0;
}
$('#img1').attr('src', '//placehold.it/128/' + banner[i])
}
setInterval(fun, 1000);
})
PoC: Demo
Here's how you can do it using jQuery:
var banner = [];
$('.imagesContainer span').each(function() {
banner.push($(this).text());
});
// you can now use the banner array here

Need Help In Javascript Text Typer Effect

I have a javascript text typer code:
CSS:
body
{
background-color:black;
}
#writer
{
font-family:Courier;
font-size:12px;
color:#24FF00;
background-color:black;
}
Javascript:
var text = "Help Please, i want help.";
var counter = 0;
var speed = 25;
function type()
{
lastText = document.getElementById("writer").innerHTML;
lastText+=text.charAt(counter);
counter++;
document.getElementById("writer").innerHTML = lastText;
}
setInterval(function(){type()},speed);
HTML:
<div id="writer"></div>
I want to know how can i use <br> tag (skipping a line or moving to another line). I tried many ways but failed, I want that if I Typed My name is Master M1nd. and then i want to go on the other line how would i go?
I've made a jQuery plugin, hope this will make things easier for you. Here is a live demo : http://jsfiddle.net/wared/V7Tv6/. As you can see, jQuery is loaded thanks to the first <script> tag. You can then do the same for the other <script> tags if you like, this is not necessary but considered as a good practice. Just put the code inside each tag into separate files, then set appropriate src attributes in the following order :
<script src=".../jquery.min.js"></script>
<script src=".../jquery.marquee.js"></script>
<script src=".../init.js"></script>
⚠ Only tested with Chrome ⚠
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery.fn.marquee = function ($) {
function findTextNodes(node) {
var result = [],
i = 0,
child;
while (child = node.childNodes[i++]) {
if (child.nodeType === 3) {
result.push(child);
} else {
result = result.concat(
findTextNodes(child)
);
}
}
return result;
}
function write(node, text, fn) {
var i = 0;
setTimeout(function () {
node.nodeValue += text[i++];
if (i < text.length) {
setTimeout(arguments.callee, 50);
} else {
fn();
}
}, 50);
}
return function (html) {
var fragment, textNodes, text;
fragment = $('<div>' + html + '</div>');
textNodes = findTextNodes(fragment[0]);
text = $.map(textNodes, function (node) {
var text = node.nodeValue;
node.nodeValue = '';
return text;
});
this.each(function () {
var clone = fragment.clone(),
textNodes = findTextNodes(clone[0]),
i = 0;
$(this).append(clone.contents());
(function next(node) {
if (node = textNodes[i]) {
write(node, text[i++], next);
}
})();
});
return this;
};
}(jQuery);
</script>
<script>
jQuery(function init($) {
var html = 'A <i>marquee</i> which handles <u><b>HTML</b></u>,<br/> only tested with Chrome. Replay';
$('p').marquee(html);
$('a').click(function (e) {
e.preventDefault();
$('p').empty();
$('a').off('click');
init($);
});
});
</script>
<p></p>
<p></p>
Instead of passing <br> char by char, you can put a \n and transform it to <br> when you modify the innerHTML.
For example (http://jsfiddle.net/qZ4u9/1/):
function escape(c) {
return (c === '\n') ? '<br>':c;
}
function writer(text, out) {
var current = 0;
return function () {
if (current < text.length) {
out.innerHTML += escape(text.charAt(current++));
}
return current < text.length;
};
}
var typeNext = writer('Hello\nWorld!', document.getElementById('writer'));
function type() {
if (typeNext()) setInterval(type, 500);
}
setInterval(type, 500);
Also probably you'll be interested in exploring requestAnimationFrame (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/), for your typing animation :)

Categories