Using jQuery to wrap each individual word and letter within each word

Imagine you have a string of text. Each letter in that string should be assigned a random font from an array.

To achieve this, I enclosed each letter within a span and randomized the font-family.

The problem with this method is word-wrap. When a sentence wraps onto a new line, individual letters break to the next line.

To solve this issue, I plan to wrap each word in a span and apply word-wrap on that span.

This means every word will have its own span. Additionally, every letter within each word will also be enclosed in a span.

I could really use some assistance with this. The example below outputs all letters and words. How can I rectify this?


var elem = $('.curiosa-type');

elem.each(function( i ) {

    var currentElem = $(this);
    var words = currentElem.text().split(" ");
    var fonts = ['&#39Times&#39', '&#39Arial&#39'];
    currentElem.empty();

    $.each(words, function (i, el) {


        currentElem.append('<span class="word">' + el + '</span>');

        var characters = currentElem.text().split("");

        console.log(characters);

            $.each(characters, function (i, el) {

                var rand = fonts[Math.floor(Math.random() * fonts.length)];

                currentElem.append("<span style='font-family:" + rand + "'>" + el + "</span");
                // check 4 white space
                if(el.indexOf(' ') >= 0){
                    //console.log(el);
                    currentElem.append('<span class="spacer"></span>');

                }

            });


    });

});


Answer №1

I modified your code by first creating a word container(div) before appending it to the DOM, instead of emptying currentElem and then reading its text (which was empty). Each word is split into characters with random font families applied. A spacer element is also added for white spaces.

var elem = $('.curiosa-type');
elem.each(function( i ) {
    var currentElem = $(this);
    var words = currentElem.text().split(" ");
    var fonts = ['&#39Times&#39', '&#39Arial&#39'];
    currentElem.empty();
    $.each(words, function (i, el) {
        console.log(words);
        // currentElem.append('<span class="word">' + el + '</span>'); //doesnt need it
        var characters = el.split('');
        var $div = $('<div>'); // create jQuery Element on fly so we can append to it even when it isn't in the DOM yet
        console.log(characters);
        $.each(characters, function (i, el) {
            var rand = fonts[Math.floor(Math.random() * fonts.length)];
            $div.append("<span style='font-family:" + rand + "'>" + el + "</span");
            // check 4 white space
            if(el.indexOf(' ') >= 0){
                $div.append('<span class="spacer"></span>');
            }
        });
        currentElem.append($div); // append our jQuery Element o the current ".curiosa-type" element
    });
});

Output:

https://i.sstatic.net/2KXzI.png

Answer №2

In my revised version, I created a new approach that may simplify the process for you in integrating it into your code.

Instead of placing each letter in a unique span element, I chose to organize the words into an array and separated them with a span tag for word-wrap functionality. Each word is assigned a random font style, allowing for proper alignment and readability even when breaking into multiple lines.

To achieve this effect, I utilized JavaScript to split the paragraph text into words and randomly assign fonts and colors from predefined arrays. This method reduces unnecessary HTML tags for individual letters, enhancing performance and efficiency within the code structure.

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

The efficiency of Ajax JSON timeouts needs improvement

Currently, I'm in the process of developing an interactive map with specific functionalities. Essentially, the user will click on a year (stored as var currentyear) and then select a country (its name stored as var thenameonly). Subsequently, an AJAX ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

I'm confused as to why my modal isn't appearing when the page loads

Recently, I've taken up coding as a hobby. However, I've encountered an issue with my modal not popping up on page load. Strangely, it works perfectly fine when I open a blank document but fails to load on my friend's homepage. I am using Dr ...

Achieve a disabled scroll bar feature on Firefox

I am experiencing an issue with a Javascript tabbed dialog where the pages have varying heights. Some of them are larger than the browser window. In Internet Explorer, there is always a scrollbar present on the right side. When it is not needed, it appear ...

Event binding done correctly

I need some clarification on proper event binding. I pasted my JavaScript code here, and someone mentioned the following: PROPER EVENT BINDING: Instead of using methods like .click(), .bind(), or .hover(), consider using the preferred .on() method. $( ...

How can I generate a bounding box with CSS?

I am a newcomer to vue.js and I have a question about creating a bounding box for any element. This bounding box resembles a view box in svg. For example, I have created a checkbox like this one: checkbox Below is the code to style the checkbox: /* checkb ...

Utilizing Jquery for independently blinking text counters

Whenever the user presses a button, a message is created and blinks 5 times. However, each time the button is pressed, all previous messages also blink along with the new one. The goal is to make only the new message blink individually 5 times upon each bu ...

How can I obtain the progress of a jQuery ajax upload?

$.ajax({ xhr: function() { var xhr = new XMLHttpRequest(); //Track upload progress xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; //Hand ...

Incorporating dropdown choices using a JSON format

Currently, I am utilizing ColdFusion 10 for retrieving data via AJAX based on the selected option from a drop-down menu. <script> function loadQuery() { var assign = $("#fcbCountry").val(); $.ajax({ type: 'get', url ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Cannot find JS variable after loop has completed

I am struggling to understand why the value of my variable is not changing in my function. Here is my code snippet: var count = function(datain){ let temparr = [], countobj = {}; $.each(datain, function(key, val) { console.log(temparr); cou ...

Changing the visibility of a div based on the height of another div using jQuery

In my code, I have a division with the class siteads where I insert js-adbanners. I also have another division with the id adblockmessage. <div class="siteads"><!-- js-code goes here --></div> <div id="adblockmessage"><!-- adblo ...

Tips on avoiding a div from causing its parent's mousemove event to activate if it is concealed

I have a collection of media content with a set of controls positioned above it. I am attempting to implement functionality where the controls will disappear when the user's mouse is inactive and reappear upon mouse movement. However, I am facing an ...

Generate an overlay div that does not impact the content of the top div

My website has a specific requirement where I need an overlay div to cover the entire body when hovering over the menu. <header><menu><ul><li class="new-menu">menu1</li></menu></header> <div id="myNav" class= ...

Personalized JQuery popup before leaving the page

Looking to display a unique jQuery dialog box with options for Yes, No, and Cancel when a user attempts to navigate away from the current page or close the window. The default browser dialog confirmation is displayed on the beforeload event, but we are tr ...

Is it possible to include og: meta information for Facebook after an Ajax load?

If you visit our website www.theshinebox.com, you'll notice that individual posts are loaded via AJAX. We want to make it possible to share or like these individual pages, but Facebook seems to be pulling information from the main page since it's ...

Activate Website Youtube Subscribe Button with a Click

Having a YouTube subscribe button on my website that doesn't match my design, I decided to create a separate button with the desired style. Additionally, I embedded the YouTube subscribe button and kept it hidden. Now, I want the hidden button to be ...

Track and store your current progress with a countdown deadline using a progress bar in Bootstrap 4

I am working on a unique way to showcase a dynamic countdown date progression using Bootstrap 4 progress bar. The challenge lies in displaying the progress percentage based on a specific date input format from an admin. After retrieving the deadline date ...

What is the best way to transfer information from a directive to a sibling element within the DOM?

Due to animation requirements, I decided to separate the directive and its value into different HTML elements. Once the directive is loaded, the separated element must be updated from the directive. How can I transmit the information from directive to ano ...

Verify if the form has a checkbox and a correctly formatted email address is not functioning as

Implementing jQuery to ensure a valid email address is entered in the input field and a checkbox is checked before showing a modal. Below is the code snippet: // Display modal when correct info is provided $('.hero--input_button').click(functi ...