Is it possible to customize the width of text color alongside a progress bar?

My Bootstrap 4 Website contains the following HTML code snippet:

<div class="container">
    <div class="row">
        <div class="col-md-6 mx-auto>
            <h2>Example heading text</h2>
            <h6>Example subheading text</h6>
        </div>
    </div
</div>

The default color of the <h2> element is black. I am performing some calculations in the background based on this text. For instance, if the calculation result is 75%, I want to change the color of the text inside the <h2> element to red, but only up to 75% of the total text width (as shown in the example picture I added).

In addition, I want to include a progress bar beneath the text (between the <h2> and <h6> elements) filled with the same red color as the text above, extending to the same width (e.g., 75%).

Is there a way to achieve this using Javascript or jQuery? Alternatively, is there a CSS-only solution that can be implemented for multiple sections on my site, each with potentially different percentage values? Both elements should be colored in a sliding or linear effect simultaneously.

I have provided an example image for better clarity on what I am aiming for. Feel free to ask for further details if needed. https://i.stack.imgur.com/kIDsA.png

Answer №1

The concept here is to extract the current value from a progress bar and use it as the color-stop values for two different colors, mimicking the behavior of a progress bar.

Below is a snippet of sample code based on your original code snippet.

In this demonstration, I opted not to utilize a progress bar. Instead, I utilized a for loop in conjunction with an alert function to demonstrate how the idea could be implemented. The iterations in the loop simulate a process that has a certain value at any given point, similar to a progress bar. By inserting this value into the gradient, the text color will change accordingly.

Keep in mind that this is simply a proposed solution.

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

    <style>
        .colorIt {
            display: inline-block;
            /*background-image: linear-gradient(to right, green 10%, black 10%);*/
            -webkit-text-fill-color: transparent;
            -webkit-background-clip: text;
            -moz-background-clip: text;
            background-clip: text;
        }

        h2 {
            font-size: 30px;
            font-weight: bold;
        }

    </style>
    <script>
        // Function to adjust the color-stops on the gradient

        $(document).ready(function () {
            adjustColorStops();
        });

        function adjustColorStops() 
        {
            var i;
            for (i = 0; i < 110; i++)
            {
                alert(i);   
                $(".colorIt").css("background-image", "linear-gradient(to right, green " + i + "%, black " + i + "%)");
                i += 9;
            }
            return;
        }
    </script>
</head>

<body>

    <div class="container">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <h2 class="colorIt">Example Heading Text</h2>
                <h6>Heading Text with Gradient Filling.</h6>
                <!--<div class="progressBarDiv"></div>-->
            </div>
        </div>
    </div>


</body>
</html>

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

How can I style the inner div by adding a class to the first div?

In my project, I have a list of elements that are generated dynamically, all styled the same way but with different content. The first element has a specific styling, and if it doesn't render, I want the second element to inherit that styling. < ...

A website with two distinct pages, where only the first page is refreshed

I have split the content of my HTML page into 2 separate subpages, based on the references provided below: Multiple distinct pages in one HTML file This is how my code is structured: ... <script> function show(shown, hidden) { document.getEle ...

Access the value of a JSON property, return null if the key is not found, all in one line of JavaScript code

How about a fun analogy in Python: fruits_dict = {"banana": 4, "apple": 3} num_apples = fruits_dict.get("apple", None) num_oranges = fruits_dict.get("orange", None) print(num_apples, num_oranges) The result would be: 3 None If we switch gears to Jav ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

Retrieve the content from a textarea and insert it into a different textarea with additional text included

Users can input HTML codes into a textarea named txtar1. A 'generate' button is available; Upon clicking the 'generate' button, the content of txtar1 will be transfered to another textarea named txtar2 with additional CSS code. Here&ap ...

Load Form with Json Data from LocalStorage Key-ID to Auto-Populate Fields

After successfully setting the ID in localStorage, I now need to retrieve and display only that specific record from my JSON data. The content of my localStorage is: This information is obtained from my JSON data after a button click. The challenge is us ...

Access the document on the desktop and open it in a new popup window

As a novice in html coding, I'm wondering if it's possible to write window size and other properties directly into the page. Let me explain. I'm currently working on a calculator and I want to run the HTML file on my desktop. Everything wor ...

Pattern for identifying JavaScript import declarations

My task involves using node to read the contents of a file. Specifically, I am looking to identify and extract a particular import statement within the file that includes the "foo-bar" package. The goal is to match only the line or lines that contain the ...

Ways to execute a script from termly on NextJS using JSX

I've been utilizing termly to assist in creating legal terms for a website I'm developing. They provided me with some HTML containing a script, but I am struggling to get it to execute on a page in JSX. I attempted to use both Script and dangerou ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Unused DIV elements in jQueryUI are identified using XSLT

Just a heads-up, I'm new to xslt so please bear with me if this seems like a silly question. In my xsl:template I have created a div element like this: <div id="objectLocked"> This object is locked by another user. Do you want to remove the lo ...

Prevent jQuery UI dialog from adjusting its position relative to the browser when scrolling

When I launch a jQuery UI dialog, the position of the dialog changes when I scroll the browser. How can I make it remain in the same position relative to the browser window? ...

Create a stylish bottom border exclusively for the text that has been wrapped

My goal is to create an underline that perfectly fits the width of the text on the bottom row, without extending beyond it. The desired effect is shown in Figure 1. Figure 1 Here is the HTML I am currently using: <h2><span class="inline-block"& ...

My goal is to design a dynamic textbox for a website that allows users to customize the text in any format they desire

I want to create a versatile textbox on my website that allows users to change the text format as they desire. Unfortunately, I am facing some issues with implementing this feature. Here is the code I have developed so far. <body> <h1>< ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Rings that react to both width as well as height

Below is a popular CSS markup for creating responsive circles. http://jsfiddle.net/WTWrB/355/ <div class="circle"></div> .circle { width: 25%; height:0; padding-bottom: 25%; -moz-border-radius: 50%; -webkit-border-radius: ...

Is there a way to customize the pagination dots in react-native-swiper-flatlist?

Is it possible to customize the pagination dots style for react-native-swiper-flatlist? <View style={styles.container}> <SwiperFlatList autoplay={false} autoplayLoop={false} index={0} showPagination ...

Manipulating Object Properties in the Browser's Console

When I log a JavaScript object in the browser, my curiosity leads me to expand it in the console window. An example of this is: console.log(console); I discover what's inside, but then a thought crosses my mind. When I dig deeper and expand the obje ...