Is it possible to alter the color of the text "midway" within a character on a website?

In some desktop applications, I've noticed a cool feature where the color of text changes as the background evolves. This allows for multiple colors on a single character, which is especially useful when displaying progress bars with percentages inside. Typically, a darker background color is used as the progress bar color. As the progress continues, the dark text might not stand out enough against the dark background, prompting the text color to change once it overlaps with the progressing bar. The image below illustrates this concept:

At 0% progress, the text appears black without a dark background. When the background reaches 100% progress, the text turns completely white. In between, at 50% progress, the text is a blend of black and white, split right on the "0" character in the example shown here.

Is there a way to achieve this effect on a webpage using CSS, images, jQuery, or any other methods? I'd prefer to avoid Flash or Java applets and am curious about the possibility of an HTML-based solution. Thank you!

Answer №1

Let's dive into it:

  1. To start, create two progress bars using div elements of equal size. Make sure they are set to occupy the full width of a 100% progress.
  2. Assign one bar a black text with white background and the other a yellow text with blue background as illustrated in your example.
  3. Place the yellow/blue bar inside a parent div and expand the width of the parent upon each percentage increment. Position this parent element above the black/white bar.
  4. Don't forget to update both progress bar labels with the corresponding percentage value after every increase.

By following these steps, you can achieve the desired effect without the need to manually paint half a character. Implementing this in CSS may prove challenging as you'll have to overlay one element over the other.

The advantage of this approach is the ability to display partially filled characters. Alternatively, there is a jQuery plugin available for creating progress bars if needed.

Answer №2

This is quite intriguing, actually. Take a look at this progress bar. It functions smoothly in IE5.5+ and Safari 5 (the browsers I tested).

Makes use of system colors. :D

Click here for visualization

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Progress</title>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
    <style type="text/css">
.progressbar, .progressbar strong {
    display:block;
    height:1.2em
}
.progressbar, .progressbar em {
    width:10em
}
.progressbar strong, .progressbar em {
    position:absolute;
    top:0;
    left:0
}
.progressbar {
    font:status-bar;
    color:windowtext;
    background:window;
    border:1px solid windowframe;
    text-align:center;
    position:relative
}
.progressbar strong {
    background:highlight;
    width:0;
    font-weight:normal;
    overflow:hidden
}
.progressbar em {
    color:highlighttext;
    font-style:normal
}
    </style>
    <script type="text/javascript">
function progress(bar) {
    var text1 = bar.getElementsByTagName('span')[0];
    var overlay = bar.getElementsByTagName('strong')[0];
    var text2 = bar.getElementsByTagName('em')[0];
    var value = parseInt(bar.getAttribute('progress'), 10);
    value += 1;
    overlay.style.width = value / 10 + 'em';
    text1.innerHTML = text2.innerHTML = value + '%';
    bar.setAttribute('progress', value);
    if (value < 100)
        setTimeout(function() { progress(bar) }, 20);
}
window.onload = function() {
    var span = document.getElementsByTagName('span');
    for (var i = 0; i < span.length; i++) {
        if (span[i].className == 'progressbar') {
            span[i].setAttribute('progress', 0);
            var el1 = document.createElement('span');
            el1.innerHTML = '0%';
            span[i].appendChild(el1);
            el1 = document.createElement('strong');
            var el2 = document.createElement('em');
            el2.innerHTML = '0%';
            el1.appendChild(el2);
            span[i].appendChild(el1);
            progress(span[i]);
        }
    }
}
    </script>
</head>
<body>
    <p><span class="progressbar"></span></p>
</body>
</html>

Keep in mind that I utilized setAttribute to set the value for the progress bar using a custom attribute name.


Adjusting the script for actual progress

The example above is just a mock progress bar as it utilizes a timer to increment the value. To achieve real progression, you'll need to tweak the script slightly. You can modify the progress function so that it adds the value to the current one, or you can have it set the value. The latter approach is likely what you'd want to go with.

function add(bar, value) {
    bar = document.getElementById(bar);
    value = parseInt(bar.getAttribute('progress'), 10) + value;
    value = value > 100 ? 100 : value < 0 ? 0 : value;
    var text1 = bar.getElementsByTagName('span')[0];
    var overlay = bar.getElementsByTagName('strong')[0];
    var text2 = bar.getElementsByTagName('em')[0];
    overlay.style.width = value / 10 + 'em';
    text1.innerHTML = text2.innerHTML = value + '%';
    bar.setAttribute('progress', value);
}
function set(bar, value) {
    value = value > 100 ? 100 : value < 0 ? 0 : value;
    bar = document.getElementById(bar);
    var text1 = bar.getElementsByTagName('span')[0];
    var overlay = bar.getElementsByTagName('strong')[0];
    var text2 = bar.getElementsByTagName('em')[0];
    overlay.style.width = value / 10 + 'em';
    text1.innerHTML = text2.innerHTML = value + '%';
}

You can omit

value = value > 100 ? 100 : value < 0 ? 0 : value
if you ensure that the value passed to the function falls between 0 and 100.

Test it out here


Edit:

I switched from using innerText to innerHTML to ensure compatibility with Firefox. This was new information for me. Additionally, in the CSS, I changed from display:inline-block to display:block. While this means the progress bar can no longer be inline, it now works in Netscape 9.

Answer №3

Check out this alternative solution: http://jsfiddle.net/93e9pzqk/.

HTML:

<div class = "progressMeter">
    <div class = "backgroundSection">0%</div>
    <div class = "progressContainer">
        <div class = "progressBarSection">0%</div>
    </div>
</div>
<button>Start</button>

CSS:

*:not(button) {
    padding: 0;
    margin: 0;
    border: 0;
    box-sizing: border-box;
}

body {
    padding: 15px;
}

.progressMeter {
    width: 200px;
    height: 20px;
    border: 1px solid #333;
    position: relative;
    margin-bottom: 10px;
}

.backgroundSection,
.progressBarSection {
    width: 100%;
    height: 18px;
    font: normal 12px/18px Arial, sans-serif;
    text-align: center;
}

.progressContainer {
    position: absolute;
    top: 0;
    left: 0;
    width: 0%;
    overflow: hidden;
}

.progressBarSection {
    background-color: green;
    color: white;
}

JavaScript/jQuery:

$(function() {
    $("button").click(function() {
        var value = 0;
        var interval = setInterval(function() {
            if(value >= 100) clearInterval(interval);
            $(".progressMeter").find(".backgroundSection, .progressBarSection")
                             .text(value + "%")
                             .end()
                             .find(".progressContainer")
                             .css("width", value++ + "%");
        }, 10);    
    });
});

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 problem with the CSS Grid effect

Looking for assistance in creating a grid layout similar to the one on this website: Upon inspecting the page source, I found the following code snippet: http://jsfiddle.net/o45LLsxd/ <div ng-view="" class="ng-scope"><div class="biogrid ng-scope ...

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

Encountering an IndexError while iterating through a table in Selenium using Python due to a list index being out of range

Encountering IndexError: list index out of range while iterating through an HTML table but unsure about the cause. My function for iterating through the table involves clicking on web page frames and downloading files from another frame. The table consis ...

No response observed upon clicking on the li element within the personalized context menu

I created a custom context menu that pops up when you click on an li element within an unordered list. I'm trying to trigger an alert when clicking on an li item inside the context menu, but it's not working as expected. To handle this dynamic c ...

Remove Chosen Pictures (Checkbox/PHP/MySQL)

I am currently displaying images from a Database using the following HTML code: <li> <input type="checkbox" id="1" /> <a rel="gallery_group" href="images/big/1.jpg" title="Image 1"> <img src="images/small/1.jpg" alt="" ...

Having trouble getting my absolute div to center?

Check out this problem on my server at THIS LINK .login-div{ background: #fff none repeat scroll 0 0; height: 500px; left: 50%; width: 500px; right: 0; z-index: 99999; top: 20%; position: ...

Choosing from a dropdown menu by pressing keys

When I press the first letter of an option in my dropdown list, it works fine. However, if I try to press two, three, or four letters consecutively, the control vanishes. For example, if the option is 'Jquery' and I press J only, it works but pre ...

Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance. My goal was to create a div that moves back and forth using toggleClass; $('div').on('click', function() { $(this).toggleClass('active') ...

Animating pseudo-elements using Jquery

I'm having trouble animating the :after pseudo-element of my ul. Below is the CSS code I have: #slider .mypagination ul::after { content: ""; width:25%; bottom: 0; left:0; position: absolute; border-top:1px solid #7accc8; ...

Tips for integrating a "datetime" picker in your AngularJS application

Currently working on an AngularJS application. The single page has a date input that needs to be added. Date Input <input type="date" ng-model="InputDate" /> Any suggestions on how to accomplish this task? ...

Adjust the top margin of a div to match the height of the screen within an iframe, ensuring cross-browser

Trying to adjust the margin-top of a div to 100% of screen height within an iframe seems to be causing issues with jQuery, as it either returns 0 or inaccurate values. While CSS3's 100vh can work as an alternative, it may not be supported in older an ...

Reduce the flexbox container to match the dimensions of its child elements

I have a set of blocks with fixed dimensions that I want to arrange in a grid layout. Using flex-wrap: wrap, I can distribute as many blocks as possible in each row. However, I need the entire wrapped column to be centered on the page, similar to this: Th ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

The PhoneGap Android whitelist feature seems to be malfunctioning and preventing navigation to the next page

Currently, I am utilizing the jQuery function load() with the code snippet $('#result').load('http://.... #div'); to retrieve the content of an external website. Moreover, I have made modifications to the domain whitelist specifically f ...

Execute a function once all images have finished loading

My current approach involves utilizing a function to load images from an array: for (var i = 0; i < images_list.length; i++) { var img = new Image(); img.onload = function() { images_objects.push(this); ...

Rotating arrows enhance the functionality of the accordion menu

I have successfully implemented a basic accordion with rotating arrows on click. Everything is working smoothly except for one issue: When I collapse one item and then try to collapse another, the previous arrow does not return to its default state. Is ...

Use jQuery to place the initial 3 elements within a div

Currently, I am dynamically pulling content into li elements using ASP.NET. My goal is to wrap a specific div class around the first 3 li items in the list only. Here is an example: <ul class="wrapper"> <div cl ...

Utilizing Ajax to dynamically populate table columns

I have an HTML table with specific labels and styles. I am looking for a way to update the table by using the unique 'id' of each row/element and populate the data using Ajax. Can anyone provide a solution or suggestion? <table border="0" ...

Exploring the interaction between Bootstrap and AngularJS in creating unique menu functionality

UPDATE: added JSFiddle link I am currently working on creating a dynamic menu or set of options that will be populated based on server requests. The data structure I am dealing with is as follows (some unnecessary data has been omitted): { "name" : ...

Ways to implement div on hover in my table's td cells

Here is the HTML table code I have: <table border='1px'> <tr> <td id='td'>first</td> <td>last</td> <tr> <td id='td'>newFirst</td> <td>newSecond</td> </t ...