2
<body>
<div id="container">
    <div id="background"></div>
  <div id="dialog">
        <p>Hello there!</p>
    </div>
    <div id="button" onclick="showDialog()">
        <img src="images/images/sceond3.jpg" width="126" height="210" alt=""/>
    </div>
</div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>

var counter = 0;
function showDialog() {
    if (counter == 0) {
        $("#dialog p").html("Testing Second Line!");
    }
    if (counter == 1) {
        $("#dialog p").html("Testing Third Line!");
    }
    if (counter == 2) {
        window.location.href = 'third.html';
    }
    //increase counter by 1
    counter++;
}

</script>
</html>

Above is my code, is there a way to make the text in the dialog div appear in a typing effect? I've searched around and most tutorials are based on a single line and because I had multiple lines, I'm not sure how to do it. Any help would be appreciated. Thanks!

Eden Chew
  • 119
  • 1
  • 3
  • 8

1 Answers1

0

Check this Fiddle

HTML

<div id="container">
    <div id="background"></div>
    <div id="dialog">
        <p>Hello there!</p>
    </div>
    <div id="button">
        <img src="images/images/sceond3.jpg" width="126" height="210" alt=""/>
    </div>
</div>

JAVASCRIPT

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
    var counter = 0;

    function typeWriter(el,i,str) {
        if (typeof str == "undefined") var str=$(el).text();
        if (typeof i == "undefined") var i=0;
        var text = str.slice(0, ++i);
        if (text != str){
            setTimeout(function(){typeWriter(el,i,str)}, 150);
        }
        $(el).text(text);
    };

    function showDialog() {
        if (counter == 0) {
            $("#dialog p").text("Testing Second Line!");
            typeWriter('#dialog p');
        }
        if (counter == 1) {
            $("#dialog p").text("Testing Third Line!");
            typeWriter('#dialog p');
        }
        if (counter == 2) {
            window.location.href = 'third.html';
        }
        counter++;
    }

    $('#button').on('click',showDialog)
</script>
Vixed
  • 3,429
  • 5
  • 37
  • 68
  • Removing the $('#button').on('click',showDialog) at the end worked perfectly for me, thank you once again :) One question, is there a way for the starting text to be displayed with the typewriter effect too? – Eden Chew Dec 30 '15 at 12:56