Struggling to incorporate typeWriter.js into the code with no luck

I'm attempting to make this script work. The script is designed to be referenced from an external script file, but I need it to be embedded for certain reasons which I won't delve into. I believe I've set it up correctly, but it seems that when I load the file, the text just appears all at once. Can someone please point out what I'm doing wrong here?

<html>
    <script>
    document.addEventListener("DOMContentLoad", typeWriter, false);
    var typeWriter = function (selector, type, interval) {
        "use strict";
        var el = document.querySelectorAll(selector),
            i = 0,
            len = el.length,
            list = [],
            a,
            all,
            text,
            start,
            end,
            nextText,
            style,
            clear;
        for (; i < len; i++) {
            list.push(el[i]);
        }
        for (a in list) {
            all = list[a];
            text = all.innerHTML += " <span id='cursor'>|</span>";
            start = 0;
            end = 0;
            style = document.createElement("style");
            document.head.appendChild(style);
            if (typeof interval === "undefined") {
                interval = 100;
            }
            if (arguments[1] === "true") {
                clear = setInterval(function () {
                    var newText = text.substr(start, end);
                    all.innerHTML = newText += " <span id='cursor'>|</span>";
                    end = end + 1;
                    style.sheet.insertRule("@-webkit-keyframes cursor {0% { opacity : 1;}100% { opacity : 0;}}", 0);
                    style.sheet.insertRule("@keyframes cursor {0% { opacity : 1;}100% { opacity : 0;}}", 0);
                    cursor.style.fontSize = "30px";
                    cursor.style.fontWeight = "bold";
                    cursor.style.webkitAnimation = "cursor 0.5s infinite";
                    cursor.style.animation = "cursor 0.5s infinite";
                    if (newText === text) {
                        clearInterval(clear);
                    }
                }, interval);
            }
            return all;
        }
    };
    typeWriter("#para1","true",100);
</script>
<p id="para1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</html>

Answer №1

After some experimentation, I was able to find a solution. It turns out that the issue was caused by putting the function call before #para1. Moving it after resolved the problem and allowed the function to work as intended.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

SinonJS - Retrieving Property Value Prior to Stub Invocation

Currently leveraging sinon.js for stubbing functionalities where it is feasible to stub and spy on methods but not properties based on my observations. I'm interested in knowing if there's a way to verify whether state.searchText gets assigned t ...

How can custom JavaScript objects have tags set upon click?

When it comes to JavaScript object referring, things can get a bit confusing. Imagine having a tag like this: <button id='myButton'>Hello</button> Now, let's say you create a custom class in JavaScript: function myClass(){ ...

Problem with jQuery AJAX Request Resolving JSON Data

One thing I have on my first page is this function: <script> function update() { $("#notice_div").html('Loading..'); $.ajax({ type: 'GET', dataType: 'json', data: latestid, url: '2includejso ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

Sending input data without a form

Currently, I am in the process of developing a website game and facing a challenge with implementing a feature I refer to as "dialogue". Initially, I attempted to address this issue by using a form element, but encountered a problem where pressing enter o ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Unable to transfer Base64 encoded data to C# through AJAX

I'm facing an issue where a base64 string I send through ajax to an aspx page with C# code behind always arrives empty. Despite other form fields posting successfully, this particular string is not making it through. The base64 string in question app ...

React - Strategies for handling an empty array in .map() operations

Struggling with rendering an empty list in React and JavaScript, specifically for search results. The goal is to display search results after the user clicks on the search button. However, the list remains empty and does not update even after retrieving ...

Retrieve the row id from the table by clicking on a button in a modal box using jQuery

I am encountering a challenge with a small task due to my limited experience in jQuery. I have a table where each row has an icon. When the icon is clicked, a modal box appears with some content. After closing the modal box, I want to retrieve the table ro ...

Retrieving information from a function beyond the scope of Mongoose

I am currently facing an issue with my function in which I need to return the Mongoose query data so that I can use it. However, I am only able to access the sum within the .exec function. How can I manage to retrieve the sum value outside of this functi ...

Only switch a radio button when the Ajax call results in success

Within an HTML form, I am working with a group of Radio buttons that trigger an Ajax call when the onchange() event is fired. This Ajax call communicates with the server to process the value sent by the call. The response can either be a string of "succes ...

Is it necessary to register a client script again after a post-back event?

Is it necessary to re-register a client-script block on all post-backs if it is added on the first page load like this? if (this.Page.IsPostBack==false) { if (this.Page.ClientScript .IsClientScriptI ...

The Ion slider's onFinish event is triggered when the page loads, independent of any user interaction with the slider

I am facing an issue with ionslider. I have observed that the plugin triggers the onFinish action without any user interaction when the page is loaded. However, on the demo site ionden.com/a/plugins/ion.rangeSlider/demo_interactions.html, the plugin only r ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

Ways to output a string array from a JSON object containing additional attributes

On the client side, I have received a JSON object from a REST service. This object contains multiple attributes, one of which is a String array. I need guidance on how to display this array using embedded AngularJS code in HTML. Here is my JSON object: [ ...

Error: 'delay' is not recognized as a valid function

I'm encountering an error message that reads as follows: $("div.valid_box").html(data.message).css("margin-left", "145px").css("width", "520px").show().delay is not a function [Break On This Error] $(...elay(10000).hide("slow", function() { within m ...

Interactive state for associated product within list without order

I am currently working on a project that involves an unordered list with separate list items. The menu design includes product images in the top list item and the corresponding product names in the list item below. I have successfully implemented a hover s ...

When trying to convert to JSON in node, the process fails. However, the data can still be

I am currently working on converting an array to JSON in order to send it to a client. The data I see in the console is as follows: [ NL: [ true, true, true, true, true, true, true, true, true, true, true, true ], ...

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

Trying to use 'cpa' before it is initialized will result in an error

I encountered the error stated above while using this particular route: router.put('/edit/:id', async (req, res) => { const cpa = await CPASchema.findById(req.params.id).then(() => { res.render('edit', { cpa:cpa }); cons ...