Creating a countdown timer that is determined by the word count of a specific <div> element

What I have: A unique countdown timer that starts at 3 seconds and counts down to 0s.

    <div class="phrase"> This is a statement.</div>

<p>

<div style='font-family: Arial; font-size: 12px; color:gray'>
<br><span class="timer" id="s2"></span>
<script>
function countTheWords( elementName, minutes, seconds )
{
    var element, endTime, letters, lineup, msLeft, time;

    function twoDigits( n )
    {
        return (n <= 9 ? "0" + n : n);
    }

    function updateTimer()
    {
        msLeft = endTime - (+new Date);
        if ( msLeft < 1000 ) {
            element.innerHTML = "<div style='font-family: Arial; font-size: 12px; color:#eda1a1'>0:00</div>";
        } else {
            time = new Date( msLink );
            letters = time.getUTCHours();
            lineup = time.getUTCMinutes();
            element.innerHTML = (letters ? letters + ':' + twoDigits( lineup ) : lineup) + ':' + twoDigits( time.getUTCSeconds() );
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
    }

    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}

countTheWords("s2", 0, 3);//2nd value represents the minute, while 3rd denotes the seconds
</script>
</div>

What I'm attempting to do:

Modify the number of seconds in the countdown timer based on the number of words in the "phrase" div.

For instance, if the phrase contains:

"This is a statement" → 4 words → countdown timer runs from 4s to 0s

"This is statement" → 3 words → countdown timer counts down from 3s to 0s

"Another statement" → 2 words → countdown timer progresses from 2s to 0s

I've conducted an extensive search via Google but found no solution; appreciate any assistance provided.

Answer №1

To properly prepare the code, you must divide the string into an array like so:

const text = document.querySelector('.text').innerText.split(' ');

Then, make sure to update the parameter to the length of text, for example:

countdown("timer", 0, text.length);//2nd value represents minutes, while the 3rd is the array length 

JSFiddle link

Answer №2

// This function simply divides the content of a div by spaces

var totalWords = yourSentence.innerHTML.split(' ').length; //  * 1000 for setTimeout

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

Perform Action Only When Clicking "X" Button on JQuery Dialog

I have a dialog box with two buttons, "Yes" and "No", which trigger different functions when clicked. $('#divDialog').dialog({ modal:true, width:450, resizable: false, buttons: [{ text: 'Yes', ...

What is the process for transferring an object to a different file?

Currently, I am working on a web application using Node.js. In my project, I have two main files. The first one is Server.js, where I handle server actions such as going online. The second file contains a large object filled with data. I successfully impo ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

Tips for displaying lesser-known checkboxes upon clicking a button in Angular

I have a form with 15 checkboxes, but only 3 are the most popular. I would like to display these 3 by default and have an icon at the end to expand and collapse the rest of the checkboxes. Since I'm using Angular for my website, I think I can simply ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

A guide on retrieving and resetting the value of a radio button within a table

I need to create multiple radio buttons within a table using Razor syntax under ASP.NET Core MVC. Each row of the table should have an update and clear link to update the record and clear the selected radio button for that specific row. <table class=&qu ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Tips for integrating google's api.js file into my vue application

Currently, I am in the process of integrating Google Calendar into my Vue project. The steps I am following can be found at this link. Additionally, I came across an example code snippet at this URL. This is how my Vue file looks: <template> <d ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Guide to adding table classes to AJAX response tables

I am facing an issue with displaying data in a table based on the AJAX request made. The problem arises because the data displayed does not follow the pagination classes applied to the table. My table has pagination functionality where 10 records are shown ...

What are the best methods for profiling a Node.js application at a specific point in its execution?

I am currently facing performance issues with my Node application, which listens to a websocket data feed and communicates with another API. The CPU usage is normally stable at around 2-5%, but occasionally (approximately 3 times within 24 hours) the incom ...

Exploring the interception of ajax http responses beyond the scope of AngularJS

Is there a way to capture and manage http responses from outside of Angular? $httpProvider is not an option since the target script loads after Angular has initialized. I need a solution that functions similar to ajaxSuccess in jQuery. ...

Steps for assigning innerHTML values to elements within a cloned div

Currently, I am setting up a search form and I require dynamically created divs to display the search results. The approach I am taking involves: Creating the necessary HTML elements. Cloning the structure for each result and updating the content of ...

After refreshing the page in Next JS, there is a delay in loading the Swiper Js styles. The Swiper slides appear stretched while waiting for Next JS to load the styles. Any suggestions

Having an issue with my Next 14.0.3 app and tailwind CSS. I recently installed swiper JS version 11.0.5 using npm. The problem arises when I reload the page, it takes about 1 or 2 seconds for the swiper styles to load. During this time, the swiper slides s ...

Having trouble getting Angular-UI-Select to work with a basic variable on $scope?

How can you reset an array with selected values so that the values can be reselected from the dropdown? I am working with a people array where the values are initially displayed in a select dropdown. When I choose certain names, they get transferred to th ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

Designing tab navigation in React Native

Is there a specific way to customize only the ORANGE tab's style? I am curious to learn how to address this particular scenario. I have attempted various methods to modify the style of the ORANGE tab. My application utilizes navigation 5. <Tab.Navi ...

"After executing a loop in JavaScript using jquery.ajax, the success function does not perform

Having trouble passing values from a PHP file to another function in Javascript. Even after a successful FOR LOOP, nothing seems to work within the SUCCESS block. Any suggestions? url1 = 'http://localhost:81/Dashboard/admin/inc/dashboard.php'; $ ...

Customizing Material UI tooltip styles with inline CSS formatting

Currently in the process of creating a React component that utilizes the Material UI Tooltip feature. In my component, I have the need to manually reposition the Mui Tooltip by targeting the root popper element (MuiTooltip-popper). However, the Mui Toolti ...