Emphasize the words within the text box, but wait before doing

I want to create a feature where a single line of text in a <textarea> is highlighted with a time delay. Can I also choose different colors for the highlight? My goal is to have each line turn blue when clicking on individual buttons sequentially. For example, clicking the first button highlights the first line in blue, then clicking the second button highlights the second line after a 1-second delay, and finally, clicking the third button highlights the third line in yellow after a 2-second delay. I've encountered a bug where if I click the button three times quickly, the highlight doesn't work properly, but that's not a major concern for me right now. I just need help implementing the time delay and color change. Thank you!

$( document ).ready(function() {
  var str = 'line 1\nline 2\nline 3\n';
  var textNumChar = str.length;
  $('#str').val(str);
  
  startPosition = 0;
  $(".lines").click(function() {
    var tarea = document.getElementById('str');
    for(i=startPosition;i<textNumChar;i++)
    {
        if(str[i]=='\n') {
            endposition = i;
            break;
        }
    }
    tarea.selectionStart = startPosition;
    tarea.selectionEnd = endposition;
    startPosition = endposition+1;
  });
});
#container {
    float: left;
}
button {
    width: 50px;height: 30px;
}
 <script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
  <button class="lines" id="line1">line 1</button>
  <br>
  <button class="lines"  id="line2">line 2</button>
  <br>
  <button class="lines"  id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>

Answer №1

You have the option to employ the setTimeout() function to establish a delay in highlighting text based on the button id.

In addition, you can utilize the ::selection css selector to customize the selected portion of an element.

$( document ).ready(function() {
  var str = 'line 1\nline 2\nline 3\n';
  var textNumChar = str.length;
  $('#str').val(str);
  
  startPosition = 0;
  $(".lines").click(function(e) {
    var tarea = document.getElementById('str');
    for(i=startPosition;i<textNumChar;i++)
    {
        if(str[i]=='\n') {
            endposition = i;
            break;
        }
    }
    
    var time = 0;
    var tar_id = e.target.id;
    var colors;
    if(tar_id == 'line1' ) {  colors = 'red'; }
    else if(tar_id == 'line2' ) { time = 1000; colors = 'blue'; }
    else if(tar_id == 'line3' ) { time = 2000; colors = 'green'; }
    
    setTimeout(function(){
      tarea.selectionStart = startPosition;
      tarea.selectionEnd = endposition;
      startPosition = endposition+1;
      $('body').addClass(colors);
    }, time);
  });
});
#container {
    float: left;
}
button {
    width: 50px;height: 30px;
}

.red ::selection {
    color: red;
    background: yellow;
}
.blue ::selection {
    color: blue;
    background: red;
}
.green ::selection {
    color: green;
    background: blue;
}
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="container">
  <button class="lines" id="line1">line 1</button>
  <br>
  <button class="lines"  id="line2">line 2</button>
  <br>
  <button class="lines"  id="line3">line 3</button>
</div>
<textarea id="str" rows="6"></textarea>

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

Can someone explain the meaning of the paragraph in the "Index Routes" section of the React-Router documentation?

Lesson 8 of the React-Router tutorial delves into the concept of "Index Routes", outlining the importance of structuring routes in a specific way. Here are some key points from their discussion: The tutorial suggests that while setting up the initial rout ...

Tips for changing the size of a background image using JavaScript on the fly

I am a beginner in the world of programming and currently working on my very first mini-project - a word definition game. One of the challenges I am facing is related to an event listener on an input field, where I aim to change the background image every ...

Can you explain the distinction between browser.sleep() and browser.wait() functions?

Encountering timing problems with my protractor tests. Occasionally, test cases fail because of network or performance-related issues. I managed to resolve these issues using browser.sleep(), but recently discovered browser.wait(). What sets them apart an ...

Bootstrap allows for placing three radio buttons in each row within an ASP radio button list

Is it possible to display three radio buttons from the asp:RadioButtonList rblbase in one row, similar to the code below? <div class="row"> <div class="col-sm-4"> Radio1 </div> <div class="col-sm-4"> Radio2 </div> &l ...

Transferring information back and forth between jQuery and Servlet

Looking for a solution to extract data from an HTML form and send it to a servlet? Here's a sample HTML form along with the script: <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script> <s ...

Discover the method of obtaining the post id within an Ajax callback in the Wordpress

Currently, I am using the Add to cart Ajax callback, but I am facing difficulty in retrieving the post Id from it. MY OBJECTIVE: My intention is to apply the add_filter only on a specific page. Here is the PHP code in functions.php file: add_filter( &apos ...

What are the steps for expanding the functionality of the sails.js library?

I am interested in expanding sailsjs to incorporate a feature similar to rails strong params, like this: req.params.limit(["email", "password", "password_confirmation"]) I have already created an addon for this, but I want it to automatically connect to ...

Unable to redirect using wp_redirect() - URL does not change

I am using a method to randomly generate query parameters and then redirecting to the same URL with those parameters assigned. While trying to achieve this, I encountered an issue where even though I was using wp_redirect(), the URL remained unchanged and ...

Combining values and eliminating duplicates from an external API: A step-by-step guide

My API provides soccer game results in this format: results:[ { Group:"A" Home: "Fc Barcelona", Away: "Fc Porto" Score: { Home: 0, Away: 0 }, { Group:"A" Home: "AC Milan", Away: "Fc Barcelona" Score: { Home: 0, Away: 1 }, { Group:"A" Home: "FC Barcelona" ...

Replace the typical bootstrap text class with stylish and modern google material icons

As a newcomer to the world of javascript, I acknowledge that my approach may not be ideal... I'm attempting to modify the color of a material icon upon clicking it. Essentially, I want to toggle it on and off. The challenge lies in the code's in ...

Determine if Param is empty or not within the context of express.js

I am looking to create a table and populate it with all the parameters that are not empty in the parameter list provided below: http://localhost:5002/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="407535732b7008121931190539142 ...

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

Node.js delete operator not performing as anticipated

Within my node.js express application, I am fetching a user object from the database: const newUser = await User.create({ username, password, email, avatar, }) However, before sending back the response containing the user object, I ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

come together for the purpose of creating an insert statement in MySQL syntax

Good day! I have a query about creating a MySQL syntax statement for inserting data into two tables. Here is the structure of the tables: I am able to insert `userid` and `picturepath`, but I'm unsure how to also insert into the `flag` column in the ...

What seems to be causing the malfunction in this ranking function?

I created a custom function to retrieve the top five users from a JSON database. Below is the code snippet: var users = []; Object.keys(database).forEach(user => { if (!users[0]) { users[0] = user } else { var checked = false; for (let ...

How to update an array in Angular using ngModel and ngFor

I am attempting to display an array's values on a form and then allow for updating those same values in the array (using name="todos{{i}}" within the <input> tag does not work as it turns it into a string instead of an array). The curr ...

Spotify app experiencing issues with Angular's ng-repeat functionality

In my code, I am facing an issue where ng-repeat is not functioning as expected. Here is the content of my App.js file: var app = angular.module('angularjs-starter', ['jsonService', 'ngRoute', 'ngResource']) app. ...

Guide on populating a textbox with values through Ajax or Jquery

Consider the scenario where there are three textboxes. The first textbox requires an ID or number (which serves as the primary key in a table). Upon entering the ID, the semester and branch fields should be automatically filled using that ID. All three fie ...