How can jQuery and CSS automatically style HTML lists based on color?

Is there a way to automatically generate unique background colors for list elements?

Check out this html snippet that displays list items with different background-colors.

<ul>
    <li>
        <a href=#">I am the first element</a>
    </li>
    <li>
        <a href=#">I am the 2nd element</a>
    </li>
    <li>
        <a href=#">I am the 3rd element</a>
    </li>
</ul>

If you're unable to manually add class or style, using jQuery could be a solution. Here's an example:

$(document).ready(function() {
    $('.toc > ul > li').each(function(e){
        var n = $(this).children().text().length*222222;
        var h = n.toString(16).substr(0,6);
        $(this).css({'background-color':'#'+h});
        //$(this).append(h);
    });
});

The current result may not be visually pleasing, as some colors appear very similar rendering the script ineffective.

Do you have any other innovative techniques for creating visually appealing colorized lists automatically?

Answer №1

Creating an appealing visual design requires the careful selection of colors. Using random colors can result in a poor aesthetic.

var colors = "000000,22222,44444,66666,88888,a0a0a0".split(",")
$('.table-of-contents > ul > li').each(function(){
      $(this).css('background-color', colors[$(this).index()])   
})

Answer №2

Check out this helpful resource:

JavaScript Random Color Generator

I've also implemented it in a code snippet on JSFiddle:

http://jsfiddle.net/3exK5/

var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.round(Math.random() * 15)];
}
    $(this).css({'background-color':''+color+''});

Answer №3

For those in search of a variety of random colors that share a similar aesthetic, consider utilizing the hsl() function to specify your color choices.

An example would be...

hsl( randomNumberBetween0and360, 100%, 50% );

This method will generate a collection of colors that complement each other seamlessly.

Take a look at this quick demonstration: http://jsbin.com/EKediJU/1/edit?html,js,output

If compatibility with IE is a concern, consider using a helpful tool like TinyColor.

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

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

Sending data back and forth across 2 tabs within one page

I noticed a strange behavior when using multiple tabs on the same page in different modes. When I clicked a button that was supposed to fill in some inputs, the data filled in the last tab opened instead of the one I actually clicked on. The angular input: ...

Dividing a string starting from the first appearance of a specific character

I need assistance with parsing multiple lines of text found in log files following this specific format: topic, the message part, contains occasional commas. Is there a method to separate the string starting from the first comma so that I can store the t ...

Retrieve only the radio buttons that are currently visible on a form using jQuery

I have a form with numerous visible and hidden radio buttons. I am attempting to isolate only the visible radio buttons for manipulation using the code below, but it's not functioning as expected. Can someone offer assistance? $('#submitbutton&a ...

What is the process for turning off bootstrap form validation?

I am facing an issue with utilizing the default input email validation in my development project. It seems that Bootstrap, which is being used for the website, has its own validation mechanism. Whenever I begin typing in a Bootstrap input field, an error m ...

Bootstrap 4 radio buttons are not aligning properly with the padding

There seems to be an issue with the alignment of Bootstrap 4 custom radio buttons and my left padding. Here is a snippet: https://i.sstatic.net/vWTNo.png This is part of the code for displaying an item <div class="p-4"> <ul class="d-flex ...

Difficulty with BCRYPT retrieving information from MySQL

As a beginner in programming, I've hit a roadblock and can't seem to find any solutions. I've managed to successfully register users into my database and hash their passwords. Now, I'm trying to implement a login feature for these users ...

"Sending data from a web page to a server-side script using AJAX: A step

I am struggling to pass a variable from the view file to the include_player_id in the controller file using AJAX in order to execute a function. This has been quite challenging for me so far. If someone could assist me with this, it would be greatly appre ...

Express.js app does not seem to properly handle app.use(express.raw()) functionality

I am in the process of creating an Express application that is designed to handle binary post data. The code snippet below showcases my progress so far: Server-side: var express = require('express'); var app = express(); var PORT = 3000; app.us ...

Local host's attempt to retrieve data from an external site via an Axios GET request was rejected

I'm currently attempting to execute a GET request on an external website in order to scrape some information. Unfortunately, my axios GET request is returning a connection error. I suspect that this issue may be related to the fact that I am sending t ...

Stop tooltips from appearing on hyperlinks in Internet Explorer

Is there a solution to disabling the pesky tooltips that appear in the bottom left corner of IE when hovering over links? Alternatively, is there a method to customize the text that appears instead of the default tooltip when hovering over a link (I attem ...

Flickering observed in AngularJS UI-Router when navigating to a new route

In my AngularJS ui-router setup, I am facing an issue with flickering during state changes while checking the authentication state. When a user is logged in, the URL /#/ is protected and redirects to /#/home. However, there is a brief flicker where the c ...

Troubleshooting issue: Unable to send file data using jQuery AJAX request

I'm having trouble sending data with a file using jQuery ajax. The code snippet I'm using is as follows: <script> function uploadImage() { var form = document.getElementById("table").value + "-form"; alert(form); ...

Guide to using two UI grids simultaneously with the directives ng-hide and ng-grid

As a newcomer to AngularJS, I am attempting to create a page with two ui-grid elements and a button labeled "other-grid". The goal is for the first grid to load initially, and when clicked again, it should be replaced by the second grid. However, I am en ...

The Angular 6 ngb-bootstrap modal fails to display due to conflicting bootstrap css within a div element

I've encountered numerous inquiries about modal not displaying, and although I've successfully implemented it in other scenarios, this one presents a unique challenge! In my Wordpress project, I've embedded an Angular app within the admin a ...

Tips on preventing conflicts between jQuery FancyBox and mouse scrolling

<script src="js/jquery-1.9.1.js"></script> <?php include("fancybox/fb.php"); ?> <script type="text/javascript" src="js/jquery.slimscroll.js"></script> <script type="text/javascript"> ...

In my Cordova application, I am able to print the locally stored JSON array, but I am encountering an issue where the

Hello, I'm having some difficulties with JSON as a beginner. I've tried searching extensively but haven't found a solution that works for me. My issue arises when attempting to save data using local storage in JSON format - the array prints ...

organize multiple blocks in the middle of the page (html)

This code is unique and belongs to me. <html> <head><title>HOME||~All About EDM~</title> </head> <body > <center><img src="edm1.jpg" alt="edm" width="950" height="250"></body></center> <c ...

How can the end event of a custom CSS animation be bound using jQuery or JavaScript?

We are currently managing multiple animations on the same object and need to execute different actions once each animation is complete. At present, we listen for the webkitAnimationEnd event and use a complex if/then statement to handle each animation sep ...

How come the name of the file is not showing up in the file input after picking a file?

I am having an issue with some html/css that uses bootstrap for file selection. Despite selecting a file, the name of the file doesn't show up in Firefox or Chrome on Mac. <div class="custom-file"> <input type="file" class="custom-file-in ...