Gauge Chart With Needle in JavaScript

Gauge Chart With Needle in JavaScript
Code Snippet:Gauge Chart
Author: Bruno Carvalho
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 1,574
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code creates a Gauge Chart with a needle for displaying data. It uses the DevExpress library to build and customize gauge charts. The major functionality of this code is to initialize and display multiple gauge charts with different values and titles. It also includes a button to generate random values for the gauges, allowing you to visualize different data points easily.

You can use this code to implement dynamic and visually appealing gauge charts with needles in your web applications. It’s beneficial for displaying data such as temperature, progress, or any value with a range.

How to Create Gauge Chart With Needle in JavaScript

1. First, ensure you include the required CSS (Reset CSS and Google Fonts) and JavaScript libraries (jQuery and DevExpress JS) by adding the following script tags to your HTML file’s <head> section:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:400,700'>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js'></script> 
<script src='https://cdn3.devexpress.com/jslib/17.1.6/js/dx.all.js'></script>

2. Create the HTML structure for your gauge charts. You can embed the following code into your HTML file:

<main class="main">
  <button id="random" class="button">Random value</button>
  <h1 class="main__title">Gauge Chart</h1>
  
  <div class="gauge-container">
    <div class="gauge"></div>
    <div class="gauge"></div>
    <div class="gauge"></div>
  </div>
</main>


<svg width="0" height="0" version="1.1" class="gradient-mask" xmlns="http://www.w3.org/2000/svg">
  <defs>
      <linearGradient id="gradientGauge">
        <stop class="color-red" offset="0%"/>
        <stop class="color-yellow" offset="17%"/>
        <stop class="color-green" offset="40%"/>
        <stop class="color-yellow" offset="87%"/>
        <stop class="color-red" offset="100%"/>
      </linearGradient>
  </defs>  
</svg>

3. Style your gauge charts and the overall layout with CSS. The following CSS code includes styles for backgrounds, colors, and positioning. You can customize this CSS to match your application’s design.

* {
  box-sizing: border-box;
}

body {
  background-image: linear-gradient(140deg, #212629, #395467);
  min-height: 100vh;
  color: #fff;
  font-family: "Open Sans", sans-serif;
  position: relative;
  padding-top: 80px;
}

a {
  color: #5f89a7;
  text-decoration: none;
}

.color-red {
  stop-color: #e23131;
}

.color-yellow {
  stop-color: #fbe500;
}

.color-green {
  stop-color: #25cd6b;
}

.main {
  max-width: 1200px;
  margin: 0 auto;
}
.main__title {
  text-align: center;
  font-size: 48px;
}

.gradient-mask {
  visibility: hidden;
}

.button {
  position: absolute;
  right: 40px;
  top: 40px;
  border: 2px solid #fff;
  background-color: #26323a;
  color: #fff;
  font-weight: bold;
  font-size: 16px;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: 0.2s;
}
.button:active {
  transform: translateY(3px);
  outline: 0;
}
.button:hover, .button:focus {
  outline: 0;
  background: linear-gradient(-140deg, #212629, #395467);
}

.gauge-container {
  padding: 20px;
  margin-top: 80px;
  display: flex;
  justify-content: space-around;
}

.gauge {
  height: 220px;
  width: 300px;
}
.gauge .dxg-range.dxg-background-range {
  fill: url(#gradientGauge);
}
.gauge .dxg-line {
  transform: scaleX(1.04) scaleY(1.03) translate(-4px, -4px);
}
.gauge .dxg-line path:first-child,
.gauge .dxg-line path:last-child {
  display: none;
}
.gauge .dxg-line path:nth-child(2),
.gauge .dxg-line path:nth-child(6) {
  stroke: #ed811c;
}
.gauge .dxg-line path:nth-child(3),
.gauge .dxg-line path:nth-child(5) {
  stroke: #a7db29;
}
.gauge .dxg-line path:nth-child(4) {
  stroke: #25cd6b;
}
.gauge .dxg-elements text:first-child {
  transform: translate(19px, 13px);
}
.gauge .dxg-elements text:last-child {
  transform: translate(-27px, 14px);
}
.gauge .dxg-value-indicator path {
  transform: scale(1.2) translate(0, -5px);
  transform-origin: center center;
}
.gauge .dxg-value-indicator .dxg-title {
  text-transform: uppercase;
}
.gauge .dxg-value-indicator .dxg-title text:first-child {
  transform: translateY(5px);
}
.gauge .dxg-value-indicator .dxg-spindle-border:nth-child(4),
.gauge .dxg-value-indicator .dxg-spindle-hole:nth-child(5) {
  transform: translate(0, -109px);
}
.gauge .dxg-value-indicator .dxg-spindle-hole {
  fill: #26323a;
}

4. In the JavaScript code, the $(document).ready() function initializes the gauge charts with default values and titles. You can customize the params object for each gauge to display the data you want.

$(function () {

  class GaugeChart {
    constructor(element, params) {
      this._element = element;
      this._initialValue = params.initialValue;
      this._higherValue = params.higherValue;
      this._title = params.title;
      this._subtitle = params.subtitle;
    }

    _buildConfig() {
      let element = this._element;

      return {
        value: this._initialValue,
        valueIndicator: {
          color: '#fff' },

        geometry: {
          startAngle: 180,
          endAngle: 360 },

        scale: {
          startValue: 0,
          endValue: this._higherValue,
          customTicks: [0, 250, 500, 780, 1050, 1300, 1560],
          tick: {
            length: 8 },

          label: {
            font: {
              color: '#87959f',
              size: 9,
              family: '"Open Sans", sans-serif' } } },



        title: {
          verticalAlignment: 'bottom',
          text: this._title,
          font: {
            family: '"Open Sans", sans-serif',
            color: '#fff',
            size: 10 },

          subtitle: {
            text: this._subtitle,
            font: {
              family: '"Open Sans", sans-serif',
              color: '#fff',
              weight: 700,
              size: 28 } } },



        onInitialized: function () {
          let currentGauge = $(element);
          let circle = currentGauge.find('.dxg-spindle-hole').clone();
          let border = currentGauge.find('.dxg-spindle-border').clone();

          currentGauge.find('.dxg-title text').first().attr('y', 48);
          currentGauge.find('.dxg-title text').last().attr('y', 28);
          currentGauge.find('.dxg-value-indicator').append(border, circle);
        } };


    }

    init() {
      $(this._element).dxCircularGauge(this._buildConfig());
    }}


  $(document).ready(function () {

    $('.gauge').each(function (index, item) {
      let params = {
        initialValue: 780,
        higherValue: 1560,
        title: `Temperature ${index + 1}`,
        subtitle: '780 ºC' };


      let gauge = new GaugeChart(item, params);
      gauge.init();
    });

    $('#random').click(function () {

      $('.gauge').each(function (index, item) {
        let gauge = $(item).dxCircularGauge('instance');
        let randomNum = Math.round(Math.random() * 1560);
        let gaugeElement = $(gauge._$element[0]);

        gaugeElement.find('.dxg-title text').last().html(`${randomNum} ºC`);
        gauge.value(randomNum);
      });
    });
  });

});

That’s all! hopefully, you have successfully created a Gauge Chart with Needle in JavaScript. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X