1

Here is my current code, it's a loop to type out some text automatically when my site is loaded. The issues is it is very touch and go, it only works sometimes (generally first load, not when refreshed etc.) Can someone point out the issue?

var i = 0;   
var line_1 = " Understand their core goal.. Act upon the emotion..";
var line_2 = " Then..";
var line_3 = " Create your own luck!";
var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
var has = "";
var time = 100;
var hit = 0;
function myLoop () {      
    setTimeout(function () {
        if(all.charAt(i) == "{") {
            //has +1"<br>";  
            time = 2000;
            hit++;
            if(hit == 3){
            document.getElementsByName('cbar')[0].placeholder = 'Enter your email address to learn more';
            }

        }else{
            has += (all.charAt(i));
            time = 100;  
        }           
        if(hit == 4){
            document.getElementById('cbar').value = "";
        }else{
            document.getElementById('cbar').value = has;
        }

        if(all.charAt(i) == "{" || hit == 3){
            has = "";
        }
        i++;                    
        if (i < all.length) {            
            myLoop();            
        }                        
    }, time)
}
myLoop();
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Brock
  • 29
  • 5

3 Answers3

2

Try putting your code inside window.onload = function() {//Your code here...}; It should be enough just to wrap the following:

window.onload = function() {
  var i = 0;   
  var line_1 = " Understand their core goal.. Act upon the emotion..";
  var line_2 = " Then..";
  var line_3 = " Create your own luck!";
  var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
  var has = "";
  var time = 100;
  var hit = 0;
  myLoop();
}

The myLoop function definition should be outside the block.

Luka
  • 1,718
  • 3
  • 19
  • 29
  • While the `onload` callback will work, he doesn't need any asset to load, so a DOM ready should be technically better: http://stackoverflow.com/questions/1206937/javascript-domready . As an alternative just put your code at the footer of the page. – MarcoL Aug 27 '14 at 10:14
  • Thank you too Marcoo, I found putting it in the footer was the easiest ^^ – Brock Aug 27 '14 at 10:25
  • @MarcoCI: I agree on that, but the main problem with `DOM ready` and pure JavaScript is cross-browser compatibility, and it might be difficult to make it work accross all browsers in pure JavaScript. In that case it would be better to use `jQuery`. – Luka Aug 27 '14 at 10:38
1

Try this:

HTML:

<body onload="myFunction()">

Javascript:

function myFunction(){
//your code here
}
Syed Ali Taqi
  • 4,898
  • 3
  • 34
  • 44
0

Try this:

$( document ).ready(function() { 

// Your code here });

PS: This is JQuery though.