Utilize a Random Color Generator to Match Background Color with Border Color in Full Calendar

I'm currently developing a full calendar to showcase a clear and aesthetically pleasing schedule for my client. I am attempting to assign a unique color to each event by generating random colors on every page load using codes. However, I have encountered an issue where the border color and background color are not matching. This discrepancy is due to the fact that I am also adding a random color to the border color. When I tried storing the getRandomColor function in a variable and applying that variable to both the border and background color of each event, it resulted in all events having the same color which does not meet my objective.

Is there a way to ensure that the background color matches the border color when randomized colors are involved?

JSFIDDLE: https://jsfiddle.net/aice09/w1pxfzcm/2/

$(document).ready(function() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January starts at 0!

    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var today = yyyy + '-' + mm + '-' + dd;

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

    var genColor =getRandomColor();
    
    $('#calendar').fullCalendar({


        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay,listWeek'
        },
        defaultDate: today,
        navLinks: true, // can click day/week names to navigate views
        editable: false,
        eventLimit: true, // allow "more" link when too many events
        events: [{
            title: 'Philippine Seven Corporation',
            start: '2017-05-01',
            backgroundColor: getRandomColor()
        }, {
            title: 'Long Event',
            start: '2017-05-07',
            end: '2017-05-10',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            id: 999,
            title: 'Repeating Event',
            start: '2017-05-09T16:00:00',
            backgroundColor: getRandomColor()
        }, {
            id: 999,
            title: 'Repeating Event',
            start: '2017-05-16T16:00:00',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            title: 'Conference',
            start: '2017-05-11',
            end: '2017-05-13',
            backgroundColor: genColor,
            borderColor: genColor
        }, {
            title: 'Meeting',
            start: '2017-05-12T10:30:00',
            end: '2017-05-12T12:30:00',
            backgroundColor: genColor,
            borderColor: genColor
        }, {
            title: 'Lunch',
            start: '2017-05-12T12:00:00',
            backgroundColor: genColor,
            borderColor: genColor
        }, {
            title: 'Meeting',
            start: '2017-05-12T14:30:00',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            title: 'Happy Hour',
            start: '2017-05-12T17:30:00',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            title: 'Dinner',
            start: '2017-05-12T20:00:00',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            title: 'Birthday Party',
            start: '2017-05-13T07:00:00',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }, {
            title: 'Click for Google',
            url: 'http://google.com/',
            start: '2017-05-28',
            backgroundColor: getRandomColor(),
            borderColor: getRandomColor()
        }],
        eventClick: function(event) {
            if (event.title) {
                alert(event.title);
            }
        }
    });

});
#calendar {
    width: 100%;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--Full Calendar-->
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.min.css">
<!--Bootstrap 3.3.7-->
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div id='calendar'></div>

Answer №1

If you need getRandomColor to return the color that was previously calculated, you can add a parameter for that functionality.

$(document).ready(function() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1; //January is 0!

  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  var prevColor;

  function getRandomColor(usePrev) {
    if (usePrev && prevColor)
      return prevColor;

    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    prevColor = color;
    return color;
  }

  $('#calendar').fullCalendar({

    header: {
      left: 'prev,next today',
      center: 'title',
      right: 'month,agendaWeek,agendaDay,listWeek'
    },
    defaultDate: today,
    navLinks: true, // can click day/week names to navigate views
    editable: false,
    eventLimit: true, // allow "more" link when too many events
    events: [{
      title: 'Philippine Seven Corporation',
      start: '2017-05-01',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Long Event',
      start: '2017-05-07',
      end: '2017-05-10',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      id: 999,
      title: 'Repeating Event',
      start: '2017-05-09T16:00:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      id: 999,
      title: 'Repeating Event',
      start: '2017-05-16T16:00:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Conference',
      start: '2017-05-11',
      end: '2017-05-13',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Meeting',
      start: '2017-05-12T10:30:00',
      end: '2017-05-12T12:30:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Lunch',
      start: '2017-05-12T12:00:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Meeting',
      start: '2017-05-12T14:30:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Happy Hour',
      start: '2017-05-12T17:30:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Dinner',
      start: '2017-05-12T20:00:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Birthday Party',
      start: '2017-05-13T07:00:00',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }, {
      title: 'Click for Google',
      url: 'http://google.com/',
      start: '2017-05-28',
      backgroundColor: getRandomColor(),
      borderColor: getRandomColor(true)
    }],
    eventClick: function(event) {
      if (event.title) {
        alert(event.title);
      }
    }
  });

});
#calendar {
  width: 100%;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--Full Calendar-->
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.6/fullcalendar.min.css">
<!--Bootstrap 3.3.7-->
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div id='calendar'></div>

Answer №2

The issue at hand stems from the fact that your function is being called twice for each event. Specifically, pay close attention to the properties backgroundColor and borderColor within each object of the 'events' array. It appears that the function is being invoked twice within each object.

{
        title: 'Long Event',
        start: '2017-05-07',
        end: '2017-05-10',
        backgroundColor: getRandomColor(), //<-- right here
        borderColor: getRandomColor() , // <-- calling  again, new color!
    }, 

One potential solution off the top of my head would be to design a function that creates event objects. You can either call the 'getRandomColor' function within this event generator or pass the color as an argument.

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

Have the functionality of right clicking and selecting Paste work in the input field using style=text and a button

Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#submit').prop('disabled', true); $('#links').change(function() { $('#submit').prop('disabled ...

Is it possible to load a JS file using Node.js's `

Is there a way to load the contents of a js file into a variable without it returning as an object? How can I achieve this? server.js const file = require("./server/file.js"); ctx.body = `${file}`; // The expected output is "(function () { ...

Angular 7's URL updates, but no other actions take place

I am new to posting here and feeling quite desperate. Currently, I am working with Angular 7 and facing an issue. The problem arises when I manually enter the desired URL, everything works perfectly. However, when I use RouterLink by clicking a button, the ...

Does Firebase only send a single input value instead of a Span?

I am currently facing an issue with pushing data into my firebase database. I have successfully incorporated one user input field into the process. However, now I am attempting to include a span value in my database, which changes based on a slider that co ...

Steps for combining TypeScript and JavaScript into a single file with npm scripts

Check out my complete package.json file here. "scripts": { "build": "webpack", "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\"", "lite": "lite-server", "postinstall": "typings install", "tsc ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

Troubleshooting Problem with Flexbox and Expandable/Accordion Side Menu

I currently have a wrapper class that contains an expandable side menu and main content section positioned side by side. The side menu acts as a filter for the content displayed in the main area, but I am encountering an issue where the rows separate when ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

unable to retrieve the city name through geographical location information

I am currently using the following code snippet to retrieve the country and city names: <?php $user_ip= getenv('REMOTE_ADDR'); $geo= unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); $city= $geo["ge ...

Dynamic content is loaded on the page using AJAX before refreshing to retrieve new

I am using the FullPage.js plugin and attempting to enable navigation between pages using AJAX. While using .load();, I am able to retrieve the desired page. However, it seems that I need to reload fullpage.js since the loaded page is not active and the s ...

Adding elements to an array in Node.js

In my 'both' object, I need to store 2 arrays: eng and fr. Each of these arrays contains multiple objects. How can I transfer all values from frDisplayData to fr:[] within the 'both' object: const displayData = []; var both = {eng:dis ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

What steps can I take to ensure that the original field does not regain focus once the dialog is closed?

My users prefer not to switch from the keyboard to mouse while filling out an input form. To address this, I am using the onFocus event to display a JQuery UI Dialog. However, when I use the dialog's close(); function, the dialog reopens as the origin ...

Transitioning from Global Namespace in JavaScript to TypeScript: A seamless migration journey

I currently have a collection of files like: library0.js library1.js ... libraryn.js Each file contributes to the creation of a global object known as "MY_GLOBAL" similarly to this example: library0.js // Ensure the MY_GLOBAL namespace is available if ...

Here's a tip on how to trigger a function when the text in an input box changes using JavaScript

While using Vue, I am developing a form which includes an input box. Whenever the text in the input box changes, it should update the function setMessage. <input type="text" v-model="test" v-on:change"setMessage"> However, the issue is that the upd ...

Encountering an issue with Angular 1.6 and webpack: controller registration problem

Currently developing a small application with Angular for the frontend, and my frontend module is structured as follows: https://i.stack.imgur.com/tjfPB.png In the app.js file, the main Angular module 'weatherApp' is defined: angular.module(&a ...

How can I center two divs within a wrapper div without also centering all the text inside?

Is there a method other than using display: inline-block and text-align:center that allows us to center two divs inside a wrapper div? I prefer not to have my text centered. ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

Chrome Extension: Sending Data from Panel Window to Popup - A Step-by-Step Guide

I've been developing a Chrome extension that displays a window (popup.html) containing a button for playing videos when the extension icon is clicked. Upon clicking the play button, another window created using window.create of type panel opens up. Th ...

Exploring the capabilities of the VSCode Volar extension in a project utilizing Vue 2, Nuxt, Typescript, and the @nuxtjs composition-api

Trying to set up the Volar VSCode extension for a NuxtJS / Typescript project and facing two issues in .vue file templates. Followed the installation guide for Vue 2 and Typescript, and enabled Take Over mode. Solved some codebase issues with the extensio ...