Determine the percentage of one color in relation to another color using AngularJS

I'm trying to make a div element change color based on another div element's color.

For example:

<div style="background-color:{{main_color}};">

In a separate div, the color should be 70% lighter than the main color.

<div style="background-color:{{this color is 70% of main_color}};">

Any ideas on how I can make this work? Thanks in advance!

Answer №1

To achieve this, you can apply a percentage to each RGB component, similar to the way SASS and LESS helpers operate. This method allows you to adjust a color property within your angularjs application.

Below is an example showcasing the use of a basic API that I've developed specifically for this purpose. The API is integrated as a service in the colorized module.

Disclaimer: This module serves as a demonstration of how the task can be accomplished. It may not handle all potential errors and exceptions that could arise. Nevertheless, it is a well-crafted module that I take pride in :{D

How to Use:

angular.module('myApp', ['colorized'])    
    .controller('myController', function ($colors) {
        var $ctrl = this;

        $ctrl.myLightenColor = $colors.lighten('#000000', 50); // Lightening by 50% (gray)        
    });

The colorized module along with a simple example:

// The module
(function() {
  angular.module('colorized', [])
    .service('$colors', function() {

      this.lighten = function(src, percent) {

        var src = normalizeColor(src);

        if (!percent) return src;

        var srcRGB = colorAsArray(src),
          lightFactor = (255 * percent) / 100,
          newRGB = {
            r: limited(srcRGB.r + lightFactor, 255),
            g: limited(srcRGB.g + lightFactor, 255),
            b: limited(srcRGB.b + lightFactor, 255),
          };

        return [
          padRGBDigit(newRGB.r.toString(16)),
          padRGBDigit(newRGB.g.toString(16)),
          padRGBDigit(newRGB.b.toString(16))
        ].join('');
      }

      function normalizeColor(color) {
        if (color == undefined) color = '000000';
        if (color[0] == '#') color = color.substring(1);

        return color;
      }

      function colorAsArray(color) {
        return {
          r: parseInt(color.substring(0, 2), 16),
          g: parseInt(color.substring(2, 4), 16),
          b: parseInt(color.substring(4, 8), 16),
        };
      }

      function limited(value, limit) {
        return Math.ceil(value > limit ? limit : value);
      }

      function padRGBDigit(str) {
        return ('00' + str).slice(-2);
      }
    });
})();

// My App
(function() {
  angular.module('myApp', ['colorized'])
    .controller('myController', function($scope, $colors) {
      $scope.mySourceColor = '#000000';
      $scope.myPercentage = 50;
      $scope.myLightColor = function() {
        return '#' + $colors.lighten($scope.mySourceColor, $scope.myPercentage);
      };
    });

  angular.element(document).ready(function() {
    angular.bootstrap(document, ['myApp']);
  });
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<div ng-controller="myController">
  <input type="color" ng-model="mySourceColor">
  <input ng-style="{'background-color': myLightColor()}" type="range" ng-model="myPercentage" min="0" max="100">
  <span>
    {{ myLightColor() }}
  </span>
</div>

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

Exploring the inserted elements within the template

Is there a way to access the variable foo in AngularJS without having to add it to $scope like this: foo = bar:'awesome bar' app.constant "foo", foo ctrl = ($scope, foo)-> <div ng-controller='ctrl'> {{foo.bar} ...

What is the best method for saving HTML form data into a Node JS variable?

I am facing an issue with setting the values of HTML form inputs onto my Node JS variables. In the JavaScript code below, I am struggling to assign values to the variables "hostname" and "port," which should then be concatenated to create a new variable ca ...

improving the resolution of images on iPhone 4 from 72ppi to 326ppi

I've been exploring ways to improve the quality of buttons in my mobile design. Currently, my navigation buttons are in a 72ppi PNG sprite and I also have another set at 326ppi. I've heard that iPhone4 can automatically choose the higher resoluti ...

What is the best way to eliminate the extra spacing on the right side of my navigation bar?

Hello everyone! I am diving into the world of HTML and CSS, but I've hit a roadblock. Despite searching through various resources and forums, I can't seem to find a solution to my problem. The issue at hand involves an irritating space in my nav ...

Unable to display Plotly chart in HTML using Python

I'm currently working on building a Python dashboard using Plotly for generating graphs and HTML for the user interface. Within my app.py file, I have defined the graph and then implemented the following code snippet: graph1Plot = plotly.offline.plo ...

The functionality to Toggle submenus within a navigation menu using jQuery is not performing as anticipated

I implemented a horizontal menu using CSS, HTML, and jQuery. Clicking on a menu item displays a sub-menu. The issue I'm facing is that when one submenu is open and I click on another menu item, the new submenu opens but doesn't hide the previous ...

Having trouble finding a solution to prevent code from automatically adding a class in jQuery/JavaScript?

I am currently in the process of customizing the FlexNav Plugin. I have made a modification to allow sub-menus to open on click instead of hover. However, a new issue has arisen where it requires two clicks to open a submenu. Upon investigation, I have i ...

Slanted background div that adjusts to the screen size

I'm struggling to create a slanted angle div that remains responsive as the screen size changes. Unfortunately, my current layout breaks completely when the screen gets bigger. If you'd like to take a look at what I've been working on so fa ...

Transforming a Bootstrap 4 HTML project into Angular 9

After stumbling upon a beautiful HTML template that caught my eye, I realized it was built using Bootstrap. Luckily, I came across tutorials on how to convert such templates into Angular 6 projects, making the process seem quite straightforward (like this ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

Setting the height to 100% on the body and html tags can lead to scrolling problems

After implementing the CSS code below, I have encountered some unexpected behavior: body, html{height:100%; overflow-x:hidden} Despite vertical scrollbars appearing as intended when the page exceeds screen height, detecting the scroll event on the body e ...

Adjustable background image with no need for a scroll bar

I am looking to create a static webpage that remains fullscreen without any scrolling. My goal is to have a centered form with the background image adjusting to the window size. As a beginner, I apologize if this request seems too simple. .container { ...

Create a responsive iframe that expands to fullscreen when a button is clicked

Currently, I am using the following code to create an adaptive iframe with a fixed ratio for both width and height: <div id="game-container" style="overflow: hidden; position: relative; padding-top: 60%"> <iframe style="position: absolute; width ...

Ensuring Consistent HTML5 Page Layout Across Various Browsers Using CSS

Hey everyone, I recently created an HTML5 page and utilized the <section> tag. However, I'm encountering issues with the CSS file I'm using. It seems to work perfectly on Firefox, but the layout is all over the place when viewed on Chrome a ...

Is drag and drop functionality in Safari on iOS automatically enabled, or will I need to write code to implement it myself?

Is there a way to detect when an HTML element is being dragged and dropped specifically for Safari events? For drag and drop functionality on Safari iPad, do I need to manually detect mousemove events on HTML elements and update their positions as the mou ...

Ways to combine text styling with images, stroke effects, and shadows all at once

I am looking to enhance my text with a background image, a text-stroke, and a text-shadow. The issue I am facing is that the text-shadow appears on top of the background image. Does anyone have a solution for placing the shadow behind the image? If you te ...

Unlock the power of polymer iron-ajax by seamlessly linking input element data to the iron-ajax's body attribute

Having some trouble binding data from an input element to the "body" attribute of iron-ajax. In the past, using core-ajax in Polymer 0.5, I could easily bind values like so: <core-ajax id="ajax" method="POST" contentTy ...

Updating text color in JavaFX for a textarea

I'm having trouble getting this to work. After checking the CSS analyzer in the scene builder, it seems that changing the text color in a textarea requires something like this: .text-area .text { -fx-fill: #1e88e5; -fx-font-size: 32px; } How ...

Unable to trigger a click on the submit button using JavaScript

I'm encountering difficulties in triggering a click using JavaScript on a Mailchimp pop-up subscribe form and I require your assistance. <!-- Title & Description - Holds HTML from CK editor --> <div class="content__titleDescripti ...

Tips on utilizing jquery slideDown alongside appendTo

I am currently utilizing an ajax request to retrieve records from the database and then appending the data in HTML. However, I want the HTML to slide down once the data has been appended, but I'm unsure of how to achieve this. Below is the ajax metho ...