Gradient in Half Circle With JavaScript

How can I achieve a gradient effect within a circle using the following initial code:

HTML:

 <div class="progresss">
   <div class="barOverflow">
     <div class="bar"></div>
   </div>
   <span>10</span>%
 </div>

 <div class="progresss">
   <div class="barOverflow">
     <div class="bar"></div>
   </div>
   <span>75</span>%
</div>

SCSS:

.progresss{
    position: relative;
    margin: 4px;
    float:left;
    text-align: center;
}
.barOverflow{ /* Wraps the rotating .bar */
    position: relative;
    //overflow: hidden; /* Omit this line to grasp the trick */
    width: 145px; height: 45px; /* Half of a circle (overflow) */
    margin-bottom: -14px; /* elevate the numbers */

    &:after {
        content: '';
        position: relative;
        display: block;
        top: -75px;
        width: 145px;
        height: 90px;
        background-color: #f3f5f6;
    }
}
.bar{
    position: relative;
    top: 0; left: 0;
    width: 145px; height: 145px; /* Complete circle! */
    border-radius: 50%;
    box-sizing: border-box;
    border: 27px solid red;       /* Half is red, */
    border-bottom-color: green;  /* Half is green */
    border-right-color: green;

}

JS:

$(".progresss").each(function(){

  var $bar = $(this).find(".bar");
  var $val = $(this).find("span");
  var perc = parseInt( $val.text(), 10);

  $({p:0}).animate({p:perc}, {
    duration: 3000,
    easing: "swing",
    step: function(p) {
      $bar.css({
        transform: "rotate("+ (45+(p*1.8)) +"deg)", // 100%=180° so: ° = % * 1.8
        // 45 is to add the needed rotation to have the green borders at the     bottom
      });
      $val.text(p|0);
    }
  });
});

My desired outcome:

https://i.sstatic.net/EZ0YO.png

Answer №1

Back in the day, I experimented with creating a gradient border using CSS and discovered the common method using the CSS border-image property. However, I found a different approach that I wanted to share:

  1. Start by creating 3 nested div elements:

    • wrapper, used to hide overflow,
    • out, with the gradient background color that will be rotated,
    • in, the inner circle where percentage numbers will be displayed,
  2. Within the first wrapper, add an element to hold the percentage number and position it in the middle using position: absolute. This separates the display of percentages from the rotating elements.

  3. Make wrapper a circle and hide its overflow for better presentation.

  4. Apply a gradient background to the out element, with the bottom half green and the top half transparent, creating a circular shape due to the parent's overflow.

  5. The rest involves some math and you can view the implementation in my fiddle.

This solution may not be perfect, especially with fixed dimensions, but it is adaptable to various needs. Feel free to adjust the gradient, dimensions, and positioning as required.

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 Shopify cart.json request has encountered a setback with error 330

My current task involves using jQuery to retrieve cart data from Shopify, which I then display on another website. However, this process has suddenly stopped working. When I attempt to make the request in Google Chrome, it shows as 'failed' and u ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

Permission for geolocation must be granted every time when using Safari and mobile browsers

My website requests geolocation permission but has a recurring issue. When accessed on mobile (using Chrome or Safari) or desktop Safari, the permission prompt pops up every time a page is reloaded. However, when accessing the site on a computer with Chro ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

Looking to iterate through MongoDB using a promise and a forEach loop? I'm aiming to populate an array

I've been struggling to iterate through elements in my MongoDB database and save the values to an array. Despite putting in hours of effort, I can't seem to get it done. Here's the code snippet: //shopController.js const Product = require ...

Determine if a cookie is set in Vue.js without requiring a page refresh

My current goal with VUE is to make the login url disappear from the navigation bar as soon as the user logs in. After successfully logging in, the token cookie is set in the browser. However, the issue arises when the login url remains visible in the nav ...

Is it possible to transform a .csv document into a JavaScript array with dictionaries? Each dictionary's keys would correspond to the column headers in the .csv file, and the values would be the

Let's imagine a scenario where I have a .csv file with the column headers listed in the first row, and their respective values are provided in the subsequent rows as shown below: index,id,description,component,service 0,5,lorem ipsum,7326985,Field Ser ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...

The curious case of unusual behavior in jQuery's livequery() method

When attempting to use the jQuery plugin "livequery" to highlight certain words within dynamically generated search results, the highlighting does not appear to work! Strangely, adding an alert() function before executing the code causes the highlighting ...

JavaScript code for extracting information from a table

After analyzing the table below: <table id="cart-subtotals" cellspacing="0" class="shop_table shop_table_responsive"> <tbody> <tr class="cart-subtotal"> <th>Subtotal</th> <td data-title="Subtotal"><span ...

Exploring the possibilities of ReactJS and the sleek design of

How can I alter the background color of a RaisedButton without having the CSS class name appear in the autogenerated div? Here is the button: <RaisedButton className="access-login" label="Acceder" type="submit"/> This is the specified CSS: .acces ...

Receive information from a form and store it in an array

Struggling to figure out how to convert this into an array. I'm having trouble grasping the concept of taking input from a form and storing it in an array. In my project instructions, it clearly states: Do NOT save the input in variables and then tra ...

Setting a checkbox to true within the MUI Data Grid using my input onChange event - how can I achieve this?

I am looking to highlight the selected row in my usage input onChange event. https://i.stack.imgur.com/rp9rW.png Details of Columns: const columns = [ { field: 'part_code', headerName: 'Part Code', width: 200 }, { ...

The response from the ajax call is still pending

I am currently working on integrating MySQL data (select query) using Spring and MyBatis. I have a controller function that is called via ajax in JavaScript to retrieve the database data. For example: ajax url: /testmysql controller requestmapp ...

What could be causing the appearance of lines above and below my SVG element in the html?

I'm using an SVG to create a curved look on my web page. The SVGs are already in place and look great on desktop screens, but when viewed on mobile, I see small lines appearing above and below the SVG that I want to remove. Here are some pictures of ...

"Encountering a Prisma type error while attempting to add a new record

I am currently utilizing Prisma with a MySQL database. Whenever I attempt to create a new record (School), an error of type pops up in the console. Additionally, I am implementing a framework called Remix.run, although it does not seem to be causing the is ...

End event in NodeJS response does not activate

I'm encountering an issue with sending the response data to the client. The response is not being sent and the 'end' event is not triggered. I'm at a loss on how to resolve this issue. My objective is to send the retrieved data from red ...

Using jQuery Mobile for Enhanced PHP Form Submissions

My jquery mobile application code is not functioning properly when it comes to posting data from a form created using PHP. I even attempted using data-ajax="false", but the form still doesn't submit the data as expected. <table id="stock"> < ...

Bug in jQuery mouse hover effect causes the mouseover event to fire multiple times upon mouseout

I'm experiencing an issue with my gallery grid where a nested span displaying the title is supposed to slide up on mouseover and hide on mouseout. However, whenever the mouse moves down to the title or hovers out of the tile from the bottom, the hover ...

How to implement mouse hover functionality in C# using Selenium?

When attempting to mouse hover on a menu with multiple sub-menus, I encountered an issue where the suggested actions caused other menus to overlap and hide the intended element. Below is the recommended code snippet for hovering over the desired element: ...