Create "blinking" caret effect for javascript "typing" - javascript

So I currently have some javascript code that creates a "typing" effect. During the typing, there is a caret at the end that mimics the caret type when typing into a console. When the typing has finished, I'd like for the caret to begin blinking, just as it would within a console. Here is the code used for it:
html:
<div id="typedtext"></div>
javascript:
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter()
{
contents = ' ';
row = Math.max(0, index-scrollAt);
var destination = document.getElementById("typedtext");
while ( row < index ) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "█";
if ( textPos++ == arrLength ) {
textPos = 0;
index++;
if ( index != arrText.length ) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
Is this possible?

You can add a few CSS scripts to add blinking effect to the caret. Move the █ inside a <span> and add .blink class to it.
// set up text to print, each item in array is new line
var arrText = new Array(
"This is an example of some,",
"typed text."
);
var speed = 60; // time delay of print out
var index = 0; // start printing array at this posision
var arrLength = arrText[0].length; // the length of the text array
var scrollAt = 20; // start scrolling up at this many lines
var textPos = 0; // initialise text position
var contents = ''; // initialise contents variable
var row; // initialise current row
function typewriter() {
contents = ' ';
row = Math.max(0, index - scrollAt);
var destination = document.getElementById("typedtext");
while (row < index) {
contents += arrText[row++] + '<br />';
}
destination.innerHTML = contents + arrText[index].substring(0, textPos) + "<span class='blink'>█<span>";
if (textPos++ == arrLength) {
textPos = 0;
index++;
if (index != arrText.length) {
arrLength = arrText[index].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", speed);
}
}
typewriter();
.blink {
animation: blink-animation 1s steps(5, start) infinite;
-webkit-animation: blink-animation 1s steps(5, start) infinite;
}
#keyframes blink-animation {
to {
visibility: hidden;
}
}
#-webkit-keyframes blink-animation {
to {
visibility: hidden;
}
}
<div id="typedtext"></div>

Related

How to include hyperlink within Javascript string array?

I'm trying to add a hyperlink to the string -- and I've attempted using both .link and .innerHTML - tho I think I may be misunderstanding what I ought to do (very new to this). Below is my code:
<div id="typedtext"></div>
<script type="text/javascript">
// set up text to print, each item in array is new line
var aText = new Array(
"Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are
some words." ,"thanks a million for any help -- click here for more."
);
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter()
{
sContents = ' ';
iRow = Math.max(0, iIndex-iScrollAt);
var destination = document.getElementById("typedtext");
while ( iRow < iIndex ) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) +
"_";
if ( iTextPos++ == iArrLength ) {
iTextPos = 0;
iIndex++;
if ( iIndex != aText.length ) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
As with standard HTML, you can simply wrap your desired link in <a href='location'>text</a> whilst outputting it through your JavaScript:
// set up text to print, each item in array is new line
var aText = new Array("Hi, I'm Krishaan!", "A few words, wish I could add a link here", "Here are some words.", "thanks a million for any help--click <a href='http://www.google.com'>here</a> for more.");
var iSpeed = 100; // time delay of print out
var iIndex = 0; // start printing array at this posision
var iArrLength = aText[0].length; // the length of the text array
var iScrollAt = 20; // start scrolling up at this many lines
var iTextPos = 0; // initialise text position
var sContents = ''; // initialise contents variable
var iRow; // initialise current row
function typewriter() {
sContents = ' ';
iRow = Math.max(0, iIndex - iScrollAt);
var destination = document.getElementById("typedtext");
while (iRow < iIndex) {
sContents += aText[iRow++] + '<br />';
}
destination.innerHTML = sContents + aText[iIndex].substring(0, iTextPos) +
"_";
if (iTextPos++ == iArrLength) {
iTextPos = 0;
iIndex++;
if (iIndex != aText.length) {
iArrLength = aText[iIndex].length;
setTimeout("typewriter()", 500);
}
} else {
setTimeout("typewriter()", iSpeed);
}
}
typewriter();
<div id="typedtext"></div>
Note that as your array uses double quotes, your hyperlink will need to use single quotes!

JQuery Letters fade in randomly

This is my first time coding in JQuery. Below is my code:
var div = document.getElementById('fadeletters1'),
letters = div.textContent.split('');
while(div.hasChildNodes()) div.removeChild(div.firstChild);
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity ' + (Math.random() * 5 + 1) + 's linear';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for(var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
<div id=fadeletters1>Helllooo This is a test for the website</div>
So the letters do fade in but then in the starting of the animation, letter are kinda visible and then fades in after couple seconds. I want it to pop up from 0 visibility to 100 visibility as its fades in.
I am trying to acheive something like this site does: http://method.digital/
You're changing the rate at which the transition takes place, instead you want to change the delay before the transition starting:
var div = document.getElementById('fadeletters1'),
letters = div.textContent.split('');
while(div.hasChildNodes()) div.removeChild(div.firstChild);
for(var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity 0.6s linear',
delay = (Math.random() * 4) + 's';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.WebKitTransitionDelay = letter.style.transitionDelay = delay;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for(var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
<div id=fadeletters1>Helllooo This is a test for the website</div>
If you want to run it for multiple divs you can wait until the first is complete before moving onto the next (this example only appears to work sometimes, make sure to hit refresh before running):
function RunAnimation(target,delay) {
var div = document.getElementById(target),
letters = div.textContent.split('');
while (div.hasChildNodes()) div.removeChild(div.firstChild);
setTimeout(function(){
for (var i = 0; i < letters.length; i++) {
var letter = document.createElement('span'),
style = 'opacity 0.6s linear',
delay = (Math.random() * 4) + 's';
letter.appendChild(document.createTextNode(letters[i]));
letter.style.WebKitTransition = letter.style.transition = style;
letter.style.WebKitTransitionDelay = letter.style.transitionDelay = delay;
letter.style.opacity = 0;
div.appendChild(letter);
}
setTimeout(function() {
for (var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].style.opacity = 1;
}
}, 0);
}, delay);
}
RunAnimation('fadeletters1')
RunAnimation('fadeletters2', 5000);
RunAnimation('fadeletters3', 10000);
<div id="fadeletters1">Helllooo This is a test for the website</div>
<div id="fadeletters2">This is a second div which also fades in</div>
<div id="fadeletters3">And who knows maybe you want a third</div>
The thing is there is two delays...
One for the animation and one for a timeout. This is the timeout that really gives the effect you are looking for.
// Get the letters from the original string.
var letters = $("#fadeletters1").text().split("");
// Remove the original string.
$("#fadeletters1").text("");
// Create a span for each letters and append them to the document.
letters.forEach(function(item,index){
var span = $("<span class='fade'>").text(item);
$("#fadeletters1").append(span);
});
// Animate each spans
$(document).find(".fade").each(function(){
// Random delay
var delay = Math.random();
var letter = $(this);
// Set a timeout to animate the spans
setTimeout(function(){
letter.animate({"opacity":1},delay*1000);
},delay*3000);
});
.fade{
opacity:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fadeletters1">Helllooo This is a test for the website</div>

How to add wrapper on the word with space

In JS i need to add span as wrapper on the entire document text words.using below code i can able to add wrapper
function walk(root)
{
if (root.nodeType == 3) // text node
{
doReplace(root);
return;
}
var children = root.childNodes;
for (var i = 0;i<children.length ;i++)
{
walk(children[i]);
}
}
function doReplace(text)
{
var start = counter;
counter = counter+text.nodeValue.length;
var div = document.createElement("div");
var string = text.nodeValue;
var len = string.trim();
if(len.length == 0){
return;
}
var nespan = string.replace(/\b(\w+)\b/g,function myFunction(match, contents, offset, s){
var end = start + contents.length;
var id = start+"_"+end;
start = end;
return "<span class='isparent' id='"+id+"'>"+contents+"</span>";
});
div.innerHTML = nespan;
var parent = text.parentNode;
var children = div.childNodes;
for (var i = children.length - 1 ; i >= 0 ; i--)
{
parent.insertBefore(children[i], text.nextSibling);
}
parent.removeChild(text);
}
using above code ill get below result
input :
Stackoverflow is good
out put:
<span>Stackoverflow</span> <span>is</span> <span>good</span>
expecting result:
<span>Stackoverflow </span><span>is </span><span>good</span>
Add optional space character to your regex after the word but before the second word boundary: \b(\w+\s*)\b

Assign random number to element in javascript but avoid duplicates

Please scroll down to bold text if you want to go straight to the question
I have made a page that consists of a grid of 9 tiles (divs).
Between 1-9 of those tiles could potentially have a slider inside it.
The sliders are all setup via a jQuery each function e.g
_gridSlider.each(function(){
// count slides, setup slider etc
}); // end slider each function
Everything works fine except the sliders all change at the same time and so I want to add some diversity into the start times.
Right now I create a random ID between 1 and X (X being the number of sliders) inside of the each function for each slider like so
_gridSlider.each(function(){
var _sliderID = Math.floor((Math.random() * _numSliders) + 1);
}); // end slider each function
I then start the sliders at a different time based around this ID like so
var _sliderStart = _sliderID + '000';
setTimeout(function() {
startTimer();
}, _sliderStart);
This works fine the only problem is that it is possible for 2 or more sliders to have the same ID, what I need is to assign each slider an ID between 1 and X but make sure that each slider has a different ID.
The end result would be have 1 timer starting at 1 second, another at 2 seconds, another at 3 seconds etc
You can use this function:
function generateId(numSliders) {
var store = generateId._store;
if (!store) {
generateId._store = {};
}
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (store[id])
store[id] = true;
return id;
}
Then you can use generated id as a start time:
var sliderId = generateId(slidersNumber);
var sliderStart = sliderId; // without + '000'
UPD generateId._store keeps used IDs inside itself. In that function store is used as a property of its function, to not add redundant variable to the namespace. You can put it outside of the generateId function. For example:
var store = {};
function generateId(numSliders) {
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (store[id])
return id;
}
But in that case you're polluting the namespace with redundant variable.
store inside of the function is used just to shorten the code a little. If you want you can write:
function generateId(numSliders) {
if (!generateId._store) {
generateId._store = {};
}
do {
var id = Math.floor(Math.random()*numSliders*1000+1);
} while (generateId._store[id])
generateId._store[id] = true;
return id;
}
An example using shuffle.
function createNumberSeries(howMany) {
var result = [];
for (var count = 1; count <= howMany; count += 1) {
result.push(count);
}
return result;
}
function shuffle(obj) {
var i = obj.length;
var rnd, tmp;
while (i) {
rnd = Math.floor(Math.random() * i);
i -= 1;
tmp = obj[i];
obj[i] = obj[rnd];
obj[rnd] = tmp;
}
return obj;
}
function createDivs(ids) {
var length = ids.length;
for (var index = 0; index < length; index += 1) {
var div = document.createElement('div');
div.id = ids[index];
div.className = 'initial';
document.body.appendChild(div);
}
}
function colourDivs(howMany) {
for (var index = 1; index <= howMany; index += 1) {
setTimeout((function(id) {
return function() {
document.getElementById(id).className += ' colorMe';
};
}(index)), index * 1000);
}
}
var numSliders = 10;
var sliderIds = shuffle(createNumberSeries(numSliders));
createDivs(sliderIds);
colourDivs(numSliders);
.initial {
height: 10px;
width: 10px;
border-style: solid;
border-width: 1px;
}
.colorMe {
background-color: blue
}

Large list rendering in JavaScript

I am trying to render the list based on virtual rendering concept. I am facing some minor issues, but they are not blocking the behaviour. Here is the working fiddle http://jsfiddle.net/53N36/9/ and Here are my problems
Last items are not visible, I assume some where I missed indexing.(Fixed, Please see the edit)
How to calculate scrollPosition if I want to add custom scroll to this.
Is this the best method or any other?
I have tested it with 700000 items and 70 items in chrome. Below is the code
(function () {
var list = (function () {
var temp = [];
for (var i = 0, l = 70; i < l; i++) {
temp.push("list-item-" + (i + 1));
}
return temp;
}());
function listItem(text, id) {
var _div = document.createElement('div');
_div.innerHTML = text;
_div.className = "listItem";
_div.id = id;
return _div;
}
var listHold = document.getElementById('listHolder'),
ht = listHold.clientHeight,
wt = listHold.clientWidth,
ele = listItem(list[0], 'item0'),
frag = document.createDocumentFragment();
listHold.appendChild(ele);
var ht_ele = ele.clientHeight,
filled = ht_ele,
filledIn = [0];
for (var i = 1, l = list.length; i < l; i++) {
if (filled + ht_ele < ht) {
filled += ht_ele;
ele = listItem(list[i], 'item' + i);
frag.appendChild(ele);
} else {
filledIn.push(i);
break;
}
}
listHold.appendChild(frag.cloneNode(true));
var elements = document.querySelectorAll('#listHolder .listItem');
function MouseWheelHandler(e) {
var e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
console.log(delta);
//if(filledIn[0] != 0 && filledIn[0] != list.length){
if (delta == -1) {
var start = filledIn[0] + 1,
end = filledIn[1] + 1,
counter = 0;
if (list[start] && list[end]) {
for (var i = filledIn[0]; i < filledIn[1]; i++) {
if (list[i]) {
(function (a) {
elements[counter].innerHTML = list[a];
}(i));
counter++;
}
}
filledIn[0] = start;
filledIn[1] = end;
}
} else {
var start = filledIn[0] - 1,
end = filledIn[1] - 1,
counter = 0;
if (list[start] && list[end]) {
for (var i = start; i < end; i++) {
if (list[i]) {
(function (a) {
elements[counter].innerHTML = list[a];
}(i));
counter++;
}
}
filledIn[0] = start;
filledIn[1] = end;
}
}
//}
}
if (listHold.addEventListener) {
listHold.addEventListener("mousewheel", MouseWheelHandler, false);
listHold.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
} else listHold.attachEvent("onmousewheel", MouseWheelHandler);
}());
Please suggest me on this.
EDIT:
I have tried again and I am able to fix the indexing issue. http://jsfiddle.net/53N36/26/
But how can I calculate the scroll position based on the array list currently displayed.
Is this the best method or any other?
I think something that would make this much easier is not to try to handle scrolling yourself.
In this fiddle I show that you can let the browser handle scrolling for you, even though we are using virtual rendering.
Using .scrollTop I detect where the browser thinks the user is looking, and I draw in items based on that.
You'll note that if you set hidescrollbar to false and the user uses it to scroll, my method still runs fine.
Therefore, to calculate scroll position you can just use .scrollTop.
And as for custom scrolling, just make sure you influence the .scrollTop of #listHolder and recall refreshWindow()
CODE FROM FIDDLE
(function () {
//CHANGE THESE IF YOU WANT
var hidescrollbar = false;
var numberofitems = 700000;
//
var holder = document.getElementById('listHolder');
var view = null;
//get the height of a single item
var itemHeight = (function() {
//generate a fake item
var div = document.createElement('div');
div.className = 'listItem';
div.innerHTML = 'testing height';
holder.appendChild(div);
//get its height and remove it
var output = div.offsetHeight;
holder.removeChild(div);
return output;
})();
//faster to instantiate empty-celled array
var items = Array(numberofitems);
//fill it in with data
for (var index = 0; index < items.length; ++index)
items[index] = 'item-' + index;
//displays a suitable number of items
function refreshWindow() {
//remove old view
if (view != null)
holder.removeChild(view);
//create new view
view = holder.appendChild(document.createElement('div'));
var firstItem = Math.floor(holder.scrollTop / itemHeight);
var lastItem = firstItem + Math.ceil(holder.offsetHeight / itemHeight) + 1;
if (lastItem + 1 >= items.length)
lastItem = items.length - 1;
//position view in users face
view.id = 'view';
view.style.top = (firstItem * itemHeight) + 'px';
var div;
//add the items
for (var index = firstItem; index <= lastItem; ++index) {
div = document.createElement('div');
div.innerHTML = items[index];
div.className = "listItem";
view.appendChild(div);
}
console.log('viewing items ' + firstItem + ' to ' + lastItem);
}
refreshWindow();
document.getElementById('heightForcer').style.height = (items.length * itemHeight) + 'px';
if (hidescrollbar) {
//work around for non-chrome browsers, hides the scrollbar
holder.style.width = (holder.offsetWidth * 2 - view.offsetWidth) + 'px';
}
function delayingHandler() {
//wait for the scroll to finish
setTimeout(refreshWindow, 10);
}
if (holder.addEventListener)
holder.addEventListener("scroll", delayingHandler, false);
else
holder.attachEvent("onscroll", delayingHandler);
}());
<div id="listHolder">
<div id="heightForcer"></div>
</div>
html, body {
width:100%;
height:100%;
padding:0;
margin:0
}
body{
overflow:hidden;
}
.listItem {
border:1px solid gray;
padding:0 5px;
width: margin : 1px 0px;
}
#listHolder {
position:relative;
height:100%;
width:100%;
background-color:#CCC;
box-sizing:border-box;
overflow:auto;
}
/*chrome only
#listHolder::-webkit-scrollbar{
display:none;
}*/
#view{
position:absolute;
width:100%;
}

Categories