Is there a way to produce a unique color using Stylus CSS?

Currently, I'm utilizing Express for Node.js and Stylus as the CSS engine. While Stylus is great, I'm facing some challenges in passing color variables or generating random colors. Despite attempting to use the javascript API for stylus, I find myself confused and perhaps complicating things unnecessarily.

var stylus = require('stylus');

app.use(stylus.middleware({
  src: __dirname + '/public',
  compile: function (str, path) {
    var mylib = function(style) {
      style.define('randomColor', function () {
        return '#5f5'; // using a temporary color just to test functionality.
      });
    };
    return stylus(str).use(mylib);
  }
}));

In my stylus sheet, I have:

mainColor = randomColor()

Unfortunately, this results in the following error message:

RGB or HSL value expected, got a string #5f5

I am struggling to pass a color variable correctly from JavaScript to the Stylus sheet.

Edit:

Find my app.js file here: https://gist.github.com/4345823
And my Stylus file here: https://gist.github.com/4345839

Answer №1

Even though this response is coming in late, it's important to address valuable information - the issue at hand, as you pointed out, is that Stylus is being supplied with a string instead of an RGB or HSL color node.

In Stylus, strings are represented like this: 'text'. When these strings are compiled into CSS, they remain unchanged. What you actually need is raw CSS text, not a string.

Fortunately, Stylus provides a built-in function called unquote() to convert a string into plain CSS text:

You can simply modify the line from

mainColor = randomColor()

to

mainColor = unquote(randomColor())

However, for cleaner code in your Stylus stylesheet, consider utilizing the nodes object in the Stylus JavaScript API. When passing a function from JavaScript to Stylus, it's recommended to return a Stylus node rather than a primitive data type:

style.define('randomColor', function () {
  var randomNum = function() { return Math.floor(Math.random() * 255 + 1); },
      r = randomNum(),
      g = randomNum(),
      b = randomNum();
  return new stylus.nodes.RGBA(r, g, b, 1); // random RGB node.
});

Although documentation on Stylus Nodes may be limited, you can refer to this source for all available nodes.

Answer №2

If you're looking to create a random color, there are a few ways you can achieve this:

 var col =  rgb(' + 
              (Math.floor(Math.random() * 256)) 
             + ',' + (Math.floor(Math.random() * 256)) 
             + ','  + (Math.floor(Math.random() * 256)) + ') ;

Alternatively, you can use the following JavaScript function:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

To convert a hex color code to RGB values, you can utilize this function:

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

Answer №3

My approach involved creating classes for a variety of color arrays and utilizing javascript to dynamically alter these classes at set intervals.

// styles.css

colors = 0 30 60 90 120 150 180 210 240 270 300 330

for hue, index in colors
  color = hsl(hue, 100%, 75%)
  .bodyColor{index}
    color: lighten(color, 55%) !important
    //background-color: darken(color, 97%) !important
  .borderColor{index}
    border-color: darken(color, 65%) !important
  a.linkColor{index}, a.linkColor{index}:visited
    color: lighten(color, 85%)
  .containerColor{index}
    background-color: color !important
  a.buttonColor{index}
    color: darken(color, 75%) !important
    background-color: lighten(color, 25%)
  a.buttonColor{index}:hover
    background-color: darken(color, 50%)
    color: lighten(color, 85%) !important

// dynamicColorScript.js

(function ($) {

  $(document).bind('initialize', function (e) {
    if (!e.firstLoad) return;

    var colorIndex = 3,
      delay = 10,
      items = [
        { element: 'body', cssClass: 'bodyColor' },
        { element: '#banner', cssClass: 'borderColor' },
        { element: 'a', cssClass: 'linkColor' },
        { element: '.translucentFrame', cssClass: 'containerColor' },
        { element: 'a.button', cssClass: 'buttonColor' }
      ];

    $(document).data('colorItems', items);

    (function changeColors() {
      items.forEach(function (item) {
        $(item.element).removeClass(item.cssClass + colorIndex);
      });

      colorIndex = Math.floor(Math.random()*11);
      $(document).data('colorIndex', colorIndex);

      items.forEach(function (item) {
        $(item.element).addClass(item.cssClass + colorIndex);
      });

      setTimeout(changeColors, delay * 1000);
    })();
  });

})(jQuery);

Answer №4

Although I know my response comes quite delayed, I came across this information thanks to a quick search on Bing. The simplest method I established involves the following steps:

generateRandom(minimum, maximum)
  return Math.floor( Math.random() * (maximum - minimum + 1) + minimum )
randomColorChannelValue()
  return generateRandom(0, 255)
createRandomColor()
  return `rgb(${randomColorChannelValue()}, ${randomColorChannelValue()}, ${randomColorChannelValue()})`

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

troubleshooting angular universal with HTTPS

My angular universal app is all set up and running smoothly for POST requests on the server-side using localhost to pre-render my app. An example of a working URL would be http://localhost:8000/api/get-info. However, things took a turn when I deployed the ...

Modifying the temp variable by assigning a new value to this.value in Javascript

Using a temporary variable, I initialize a THREE.Vector3 which is then passed into the creation of an object. object[i] = new Object(new THREE.Vector3(0,0,0)); Within the Object class, there is a variable called texture that gets assigned the new THREE.V ...

Encountering a Conflict with NPM Peer Dependencies

I recently started learning AngularJS through a tutorial, even though I am completely new to it. Here is the tutorial I have been following: https://www.youtube.com/watch?v=ofASsumsf7E However, I encountered an issue when running the npm install command. ...

Square-shaped arch chart utilizing Highcharts library

For my project, I have a unique challenge of creating an Arched square chart using High Charts. Despite my efforts, I have not been able to find any suitable platform that demonstrates this specific requirement. The task at hand is outlined as follows – ...

Activate and Deactivate Link in Bootstrap Navigation Bar

After reading numerous posts on the topic and trying the same solution without success... The issue I am facing is that I want to implement Twitter Bootstrap 2.3.2 and its navbar. I have included the necessary css and js files along with jQuery. Initially ...

Tips for recognizing users in socket.io?

I'm currently developing a chat application with socket.io. However, one issue I am facing is identifying the sender of a message. Unlike in Express where we have the "req" (request) variable to easily identify users, socket.io does not provide such f ...

Create a single declaration in which you can assign values to multiple const variables

As a newcomer to react/JS, I have a question that may seem basic: I need multiple variables that are determined by a system variable. These variables should remain constant for each instance. Currently, my approach is functional but it feels incorrect to ...

Foundation Framework sidebar by Zurb

My current dilemma involves the zurb foundation framework, specifically with the .row class being set to a max-width of 61.25em, which is equivalent to 980px in width. The problem I am facing is that when I resize the browser and it reaches 1024px wide, t ...

How to retrieve session information in a Next.js page utilizing withIronSession()

My attempts to access the session using req.session.get('user') have been unsuccessful even after reading the post titled Easy User Authentication with Next.js and checking out a related question on Stack Overflow about using next-iron-session in ...

Do we need to employ strict mode when utilizing specific ES6 functions in Node.js?

There has been a debate circulating at my workplace regarding whether or not it is necessary to include 'use strict' when using ES6 in Node.js without Babel. Some argue that certain ES6 methods may not function correctly without it, but I haven&a ...

Internet Explorer struggling to function due to JavaScript errors

While Chrome and Firefox breeze through the page, it seems to hang for an eternity in Internet Explorer. Here is the problematic page: ============= Error Details: User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2 ...

Interaction between index file and module instance

As I develop a computer system, I have divided it into various smaller components. My experience in software development has taught me the value of keeping systems compact and focused. To achieve this, I am creating modules that perform specific function ...

A simple guide on accessing a local PDF file and returning it as the response for an ExpressJS application

In my ExpressJS application, I have a method for generating a PDF file and sending it to the client. However, there are cases where I need to retrieve an existing local PDF file and return it as the response. I'm unsure how to handle this scenario. ...

Secure access to the Express API with Kinde protection

I am currently working on developing a web application using next.js and a mobile application using react native. Both of these apps are integrated with my backend system which is built using node.js and express. To handle authentication, I have decided to ...

Store information in Factory and retrieve it in the controller

I am encountering an issue with my code. Below is the factory code: .factory('shareDataService', function() { var sharedData = {}; sharedData.shareData = function(dateFrom, dateTo) { var from = dateFrom; var to = dateTo ...

Guide to accessing a mongoose model that is not part of your current project

I am currently developing a microservice for a Referral System in conjunction with an existing app that already has its main backend up and running. This Microservice will serve as an extension to the current setup. I have created a Referral Model structur ...

Steps for converting a window to a PDF file rather than an XPS file

Whenever I attempt to print the contents of my HTML page using window.print(), it always creates an XPS file. However, what I really need is for it to generate a PDF file instead. Any assistance would be greatly appreciated. Thank you! ...

Having trouble with looping the CSS background using JavaScript in CodePen

Can someone help me with looping through CSS background images? Why is the background not changing in this code example: http://codepen.io/anon/pen/dGKYaJ const bg = $('.background').css('background-image'); let currentBackground = 0; ...

Exploring Next.js nested dynamic routes: utilizing getStaticProps for data fetching and sharing data across routes

I am currently working on developing a next.js application with nested dynamic routes and the need for shared data among these routes. The directory structure I have set up is as follows: -pages -/level1 -/[level1_id].js -index.js -/level2 ...

Breaking apart faces of a sphere using Three.js

I am currently working on creating a sphere geometry. geometry = new THREE.SphereGeometry( 200, 20, 10 ); material = new THREE.MeshLambertMaterial({ shading: THREE.FlatShading, color: 0xff0000 }); sphere = new THREE.Mesh(geometry, material); scene.add( sp ...