Your unique way of typing out your thoughts

This is an example of typing code using jQuery.

How do I customize my own style?

For example, I want to write a text like this:

Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice to see you</strong> guys!

However, the "Data-Text" section does not support CSS styles and HTML tags.

What should I do?

The Code:

var $typer = $('.typer'),
    txt = $typer.data("text"),
    tot = txt.length,
    ch  = 0;

(function typeIt() {   
  if(ch > tot) return;
  $typer.text( txt.substring(0, ch++) );
  setTimeout(typeIt, ~~(Math.random()*(200-60+1)+60));
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="typer" data-text="Hi! My name is Al. I will guide you through the Setup process."></span>

Answer №1

To customize the text animation, you can set the data-text attribute with an HTML string and replace .text() with .html() in the typeIt() function call.

var $typer = $('.typer'),
    txt = $typer.data("text"),
    tot = txt.length,
    ch  = 0;

(function typeIt() {   
  if(ch > tot) return;
  $typer.html( txt.substring(0, ch++) );
  setTimeout(typeIt, ~~(Math.random()*(200-60+1)+60));
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys!
'></span>

Another way to achieve this effect is by creating a <template> element, accessing the child nodes of the template content using .content.childNodes, converting them into an array with Array.prototype.slice.call(), and then iterating through each character of the data-text HTML string using .reduce() method along with .split("").

In the .reduce() callback, utilize promises to handle asynchronous tasks such as waiting for a specified timeout before moving to the next step. Check if the node is a text node, if so, update the HTML of $typer; otherwise, store the text content, empty the current node, append it to $typer, and gradually display each character.

var $typer = $('.typer')
    , txt = $("<template>", {
              html: $typer.data("text")
            })[0].content.childNodes;

Array.prototype.slice.call(txt).reduce(function(p, node) {
  return p.then(function() {
    var currentText = node.textContent.split("");
    if (node.nodeType !== 3) {
      var curr = node;
      $typer.append($(node).empty());
    }
    return currentText.reduce(function(promise, text) {
      return promise.then(function() {
        return new Promise(function(resolve) {
          setTimeout(function() {
            $(curr || $typer).html(function(_, html) {
              return html + text;
            });
            resolve()
          }, ~~(Math.random() * (200 - 60 + 1) + 60))
        })
      })
    }, Promise.resolve())
  })
}, Promise.resolve());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

<span class="typer" data-text='Hi. My <span style="text-decoration: underline;">name</span> is <span style="color: #ff0000;">Amir</span>. <strong>Nice too see you</strong> guys!
'></span>

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

Tips for ensuring smooth rendering of big fonts in Chrome on OSX

On my Macbook Pro running Mojave, I noticed that regular fonts appear normal, but large fonts look jagged in Chrome (unlike Safari or Firefox). You can see an example on CodePen .large { font-size: 300px; font-weight: bold; } Chrome https://i.sstat ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

A step-by-step guide on uploading images from the source using a generic handler

I have been utilizing this script to upload images using a generic handler. <script type="text/javascript"> $(function () { $('#btnUpload').click(function () { var fileUpload = $("#FileUpload1").get(0); var files = file ...

Automatically submit using Braintree Custom Form through programming

Incorporating Braintree custom form inside a Bootstrap modal has been working smoothly for me. Currently, the form functions properly with a submit button placed within it. Upon clicking the submit button, Braintree takes over and carries out its submissio ...

retrieve the URL of a freshly opened page following a click

I am currently in the process of developing a test that involves clicking on a button to open a new tab and redirecting to a different website. My objective is to retrieve the value of this website for parsing purposes, specifically after the rfp code in t ...

Ways to determine the specific element that was clicked while using event listeners within a for loop

I am currently working on creating a FAQ list where only one question can be expanded at a time. My approach involves adding event listeners in a for loop to all the question elements. However, I am facing an issue where I cannot identify which element has ...

Rendering a Subarray using Map in ReactJS

I have an object containing data structured like this: [{"groupid":"15","items":[ {"id":"42","something":"blah blah blah"}, {"id":"38","something":"blah blah blah"}]}, {"groupid":"7","items": [{"id":"86","something":"blah blah blah"}, {"id":"49","somethin ...

Trick for using :checked in CSS

Is it possible to change the color of a deep linking div using an input checkbox hack in the code below? <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /&g ...

How can I integrate CKEditor with jQuery Dialog and create a seamless user experience?

Currently, I am experimenting with integrating CKEditor and jQuery to create a pop-out editor. Here is the code snippet that I have developed so far, but unfortunately, it's not functioning as anticipated. Essentially, when the 'Edit' link i ...

How to Refresh Javascript Functionality in Rails 5 after an Ajax Update?

After exploring my Javascript issue, I've identified the problem post an AJAX call that refreshes a div's content. The core issue is that the contents within the div become unlinked or uninitialized for the Javascript. My goal is to allow users t ...

Issue with dat.gui not displaying correctly within a WebGL container

When attempting to display my dat.gui interface with a button and textbox on top of my WebGL window, I encounter this issue: https://i.sstatic.net/N9peP.png The section for "Close Controls" in the dat.gui is visible, but strangely the button and textbox ...

Bootstrap 4 Vertical Timeline Layout Showing Uneven Columns Due to Large Margins

I'm currently working on my very first website and trying to implement a vertical timeline using Bootstrap 4. My goal is to have the timeline bar situated between two columns. However, I'm encountering an issue where I can't align text in th ...

Utilize ASP.net to efficiently store and retrieve events in a SQL database

If you have an SQL database table named Calendar, here are the tasks you may want to accomplish: You can achieve the following using Ajax: Retrieve events from the database and pass a List to your website. Save events back to the database. Note that ev ...

Exploring the Relationship Between Z-Index and Overflow in a Collapsible Div Featuring Slim Select

Here is my demonstration of embedding a Slim Select dropdown within a collapsible div: CodePen Example <html> <head> <!-- MULTIPLE SELECT DROPDOWNS --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ ...

Validate form elements using jQuery and jquery.validate only when the corresponding div is displayed. Hide the validation for elements when the div

For my Form validation, I have incorporated a piece of HTML and code snippet. In my Profile Type section, I am using show/hide coding to display another div when the value 2 is selected in Profile Type. What I aim for here is that jquery.validate only vali ...

Creating infinite dynamic name selectors: A step-by-step guide

Having redundant jQuery calls is something I'm dealing with, and I would like to streamline them using a loop. $('.class1').on('click', function () { ... $('.class2').on('click', function () { ... $('.clas ...

Issues with the JavaScript "for in" iteration technique

I am working on a website menu that will be created using JavaScript and an array of objects as the foundation: [ {"menuName":"Contact Info","sectionName":"contacts"}, {"menuName":"Facilities","sectionName":"facilities"}, {"menuName":"Locations","se ...

Tips on how to retrieve a variable from an array in Vue JS

New to Javascript and Vue, I am exploring examples to grasp the fundamental concepts. <template> /*<p v-bind:class="['bold', 'italic', isValid ? 'valid' : 'invalid']">*/ <p v-bind:class= ...

Is there a way to retrieve the JavaScript constructor object by passing it as a parameter in an IIFE function?

In my first method, I have successfully created an object constructor called Person. Inside this constructor, I used an IIFE function expression which is functioning correctly. The property inside this function of Person is accessible! var Person = fun ...

What is the best way to refresh a div every 20 seconds?

I'm currently working with this script: <script id="_wauwgs">var _wau = _wau || []; _wau.push(["small", "p00ystfryeuc", "wgs"]); (function() {var s=document.createElement("script"); s.async=true; s.src="http://widgets.amung.us/small.js" ...