0

I am just working on a new website and would like javascript to assign a colour from ~10 different possible, pre-selected colours to a CSS div. The page is an index page of projects, and I'd like every project title (div.title) to take a different colour from an array. I am pretty new to javascript. Is this possible? If so, would it also be possible for it to select always the next colour in line in a loop (red, green, blue, yellow, for example, then repeat from the top)?

EDIT 01: I am customising a cargocollective website, so there are lots of limitations in terms of what can be done. I thought this way would be possible because I used the following code to change a:hover states:

$(document).ready(function()
{
$("a").hover(function(e)
{
var randomClass = getRandomClass();
$(e.target).attr("class", randomClass);
});
});

function getRandomClass()
{
//Store available css classes
var classes = new Array("red", "blue", "yellow", "navy", "orange", "green", "aqua",);

//Give a random number from 0 to 5
var randomNumber = Math.floor(Math.random()*7);

return classes[randomNumber];
}

and the applied this to the CSS:

a.red:hover { color: #f15123; }
a.blue:hover { color: #3491dd; }
a.yellow:hover { color: #f4b138; }
a.navy:hover { color: #3d57a7; }
a.orange:hover { color: #fd7b23; }
a.green:hover { color: #6fb766; }
a.aqua:hover { color: #4dd4af; }

I am trying to target div.title and would like the text colour to be different in every instance it shows up. Does that make more sense? If there's an easier way to do it, that would be great.

EDIT 02:

I am guessing my problem is the way the page is structured. I can't directly edit the HTML, only add scripts and some custom HTML. Here's what it looks like:

<div thumbnails="grid" grid-row="" thumbnails-pad="" thumbnails-gutter="" data-elementresizer="">
<div class="thumbnail has_title" data-id="6103627" grid-col="x10" thumbnails-pad="">
<a href="/Foxes-on-the-Hill" rel="history" class="image-link">
<div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
<img data-mid="30797153" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/061c5d22a0ab1b7513812587c2ccf0f078542537cb129f9cd92159f26c925f80/1.jpg">
</div>
<div class="title"><span>Foxes on the Hill</span></div>
</a>
 <div class="tags"><a href="/Cartography" rel="history">Cartography</a>            </div>
</div>
<div class="thumbnail has_title" data-id="6103628" grid-col="x10" thumbnails-pad="">
<a href="/The-Curtains-in-the-House-of-the-Metaphysician" rel="history" class="image-link">
<div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
<img data-mid="30797166" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/8be578d25086d836423959cda5323088cf6305bc0de35d102105a0ea46a75235/2.jpg">
</div>
<div class="title"><span>The Curtains in the House of the Metaphysician</span></div>
</a>
<div class="tags"><a href="/Illustration" rel="history">Illustration</a></div>
</div>
<div class="thumbnail has_title" data-id="6103629" grid-col="x10" thumbnails-pad="">
<a href="/The-Common-Life" rel="history" class="image-link">
<div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial; will-change: opacity, transform;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
<img data-mid="30797176" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/77a8b7c4d5a46922dea1c1484793a1d7b204f60a4bbf4d9d22d2276d4c085cc2/3.jpg">
</div>
<div class="title"><span>The Common Life</span></div>
</a>
<div class="tags"><a href="/Dimensionality" rel="history">Dimensionality</a></div>
</div>
</div>

And the CSS that goes with it:

/**
 * Thumbnails
 */

div[thumbnails] {
justify-content: flex-start;
}

[data-css-preset] .thumbnails {
background-color: rgba(0, 0, 0, 0)/*!thumbnails_bgcolor*/;   
}

[data-css-preset] .thumbnails_width {
width: 100%/*!thumbnails_width*/;
}

[data-css-preset] [thumbnails-pad] {
padding: 1.5rem/*!thumbnails_padding*/;
}

[data-css-preset] [thumbnails-gutter] {
margin: -3rem/*!thumbnails_padding*/;
}

[data-css-preset] [responsive-layout] [thumbnails-pad] {
padding: 0.5rem/*!responsive_thumbnails_padding*/; 
}

[data-css-preset] [responsive-layout] [thumbnails-gutter] {
margin: -1rem/*!responsive_thumbnails_padding*/; 
}

.thumbnails .thumb_image {
outline: 0px solid rgba(0,0,0,.12);
outline-offset: -1px;
}

.thumbnails .title {
margin-top: 1.2rem;
margin-bottom: 0.2rem;
font-size: 1.7rem;
font-weight: 400;
color: rgba(0, 0, 0, 0.85);
font-family: Interstate, Icons /*!Persona*/;
font-style: normal;
line-height: 1.3;
text-align: left;
}

.thumbnails .tags {
margin-top: 1.2rem;
margin-bottom: 0.5rem;
font-size: 1.7rem;
font-weight: 400;
color: rgba(0, 0, 0, 0.35);
font-family: Interstate, Icons /*!Persona*/;
font-style: normal;
line-height: 1.3;
text-align: left;
}

.thumbnails .tags a {
border-bottom: 0;
color: rgba(0, 0, 0, 0.25);
text-decoration: none;
}

.thumbnails .has_title .tags {
margin-top: 0rem;
}

It is the .title that I am trying to target, but nothing really seems to work. Thanks again!

8
  • 4
    Welcome to SO. Please read this how to ask Your current question shows no effort at all. You need to provide the code you have tried and ask more specific question. Commented Dec 17, 2018 at 14:42
  • 1
    Why do you need JavaScript? based on CSS selectors you can do it... but if you want to do it with JavaScript, select the elements and loop over them. Seems pretty straight forward. Commented Dec 17, 2018 at 14:42
  • 2
    Also java is not javascript :) Commented Dec 17, 2018 at 14:43
  • What do you mean by "assign colour to CSS"? Do you mean you want to modify the CSS file using Javascript? But why? There are options for both pure CSS solution and simply setting colors into styles of specific DOM elements. Commented Dec 17, 2018 at 14:45
  • Sorry guys, first time here. Let me edit the question and try to expand it. Commented Dec 17, 2018 at 14:46

4 Answers 4

2

There is no need for JavaScript if you can select the items with CSS using nth child.

div.foo:nth-child(7n+1) a:hover  { color: #f15123; }
div.foo:nth-child(7n+2) a:hover  { color: #3491dd; }
div.foo:nth-child(7n+3) a:hover  { color: #f4b138; }
div.foo:nth-child(7n+4) a:hover  { color: #3d57a7; }
div.foo:nth-child(7n+5) a:hover  { color: #fd7b23; }
div.foo:nth-child(7n+6) a:hover  { color: #6fb766; }
div.foo:nth-child(7n+7) a:hover  { color: #4dd4af; }
<div class="foo"><a href="#">Link 1</a></div>
<div class="foo"><a href="#">Link 2</a></div>
<div class="foo"><a href="#">Link 3</a></div>
<div class="foo"><a href="#">Link 4</a></div>
<div class="foo"><a href="#">Link 5</a></div>
<div class="foo"><a href="#">Link 6</a></div>
<div class="foo"><a href="#">Link 7</a></div>
<div class="foo"><a href="#">Link 8</a></div>
<div class="foo"><a href="#">Link 9</a></div>
<div class="foo"><a href="#">Link 10</a></div>
<div class="foo"><a href="#">Link 11</a></div>
<div class="foo"><a href="#">Link 12</a></div>
<div class="foo"><a href="#">Link 13</a></div>
<div class="foo"><a href="#">Link 14</a></div>

Based on your edit:

div.thumbnail:nth-child(7n+1) a:hover .title { color: #f15123; }
div.thumbnail:nth-child(7n+2) a:hover .title { color: #3491dd; }
div.thumbnail:nth-child(7n+3) a:hover .title { color: #f4b138; }
div.thumbnail:nth-child(7n+4) a:hover .title { color: #3d57a7; }
div.thumbnail:nth-child(7n+5) a:hover .title { color: #fd7b23; }
div.thumbnail:nth-child(7n+6) a:hover .title { color: #6fb766; }
div.thumbnail:nth-child(7n+7) a:hover .title { color: #4dd4af; }
<div thumbnails="grid" grid-row="" thumbnails-pad="" thumbnails-gutter="" data-elementresizer="">
  <div class="thumbnail has_title" data-id="6103627" grid-col="x10" thumbnails-pad="">
    <a href="/Foxes-on-the-Hill" rel="history" class="image-link">
      <div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
        <img data-mid="30797153" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/061c5d22a0ab1b7513812587c2ccf0f078542537cb129f9cd92159f26c925f80/1.jpg">
      </div>
      <div class="title"><span>Foxes on the Hill</span></div>
    </a>
    <div class="tags"><a href="/Cartography" rel="history">Cartography</a> </div>
  </div>
  <div class="thumbnail has_title" data-id="6103628" grid-col="x10" thumbnails-pad="">
    <a href="/The-Curtains-in-the-House-of-the-Metaphysician" rel="history" class="image-link">
      <div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
        <img data-mid="30797166" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/8be578d25086d836423959cda5323088cf6305bc0de35d102105a0ea46a75235/2.jpg">
      </div>
      <div class="title"><span>The Curtains in the House of the Metaphysician</span></div>
    </a>
    <div class="tags"><a href="/Illustration" rel="history">Illustration</a></div>
  </div>
  <div class="thumbnail has_title" data-id="6103629" grid-col="x10" thumbnails-pad="">
    <a href="/The-Common-Life" rel="history" class="image-link">
      <div class="thumb_image scroll-transition-fade" style="height: 0px; padding-bottom: 100%; transition-duration: initial; will-change: opacity, transform;" data-elementresizer-no-resize="" data-elementresizer-no-centering="">
        <img data-mid="30797176" width="1200" height="1200" style="width: 100%; height: auto;" src="//freight.cargocollective.com/w/750/i/77a8b7c4d5a46922dea1c1484793a1d7b204f60a4bbf4d9d22d2276d4c085cc2/3.jpg">
      </div>
      <div class="title"><span>The Common Life</span></div>
    </a>
    <div class="tags"><a href="/Dimensionality" rel="history">Dimensionality</a></div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

6 Comments

This may be the more sensible way to do this :-)
Why use JS when CSS does it all
Thanks! This would be a nice solution, but it doesn't seem to work on cargocollective. I tried applying to the links but I only get the first colour when hovering. :/
@eeeriver well impossible for me to know why it would not work since I have no clue what the HTML structure is.
@espascarello I just added it up there. i don't have direct access to it so I copied it from my browser. please excuse the mess. Thank you so much for looking into it!
|
0

Yes it is possible.

Here is some sample HTML:

<div class="title">1Test</div>
<div class="title">2Test</div>
<div class="title">3Test</div>

Here is the script that changes the color attribute of the above elements:

const arrColor = ['red','green','blue'];

const elements = document.querySelectorAll('div.title');

elements.forEach( 
  function(el, in) { 
    el.style.color = arrColor[in];
  });

Make sure that arrColor has at least the same amount of elements as your div.title s, otherwise in the forEach loop in argument will go above the available index in arrColor.

Here it is shared on codepen: https://codepen.io/kevindelsh/pen/zyBeXq

3 Comments

That seems to work! Thanks for the super quick response. Do you think it would be possible to use the same to affect hover states instead of the code I posted above?
Unfortunately not. That's because we are setting inline styles here and inline styles don't accept pseudo classes like :hover. For this you need to change css classes. This can be done with the same code and just some small edits. I can add that to the answer if you like.
Actually, this worked out on the preview but when I try to save it it says the code is broken, and when I view the page it doesn't work. Could it be? Or is it maybe incompatible with cargocollective?
0

Here's a small function that will return a starting random color and the following ones:

function colorSelector(colors) {
  let index = Math.floor(Math.random() * colors.length) - 1;
  return function() {
  index = index >= colors.length - 1 ? 0 : index + 1; 
    return colors[index]
  }
}
const selectedColors = ['#e8e8e8','#d9d9d9','#a5b4d3'];
const selectColor = colorSelector(colors);

selectColor(); // will return the color
selectColor(); // will return the next one in the list

Comments

0

You can try this - HTML:

<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>
<h3 class='test'>Test</h3>

CSS:

.red{
  color:#FF0000;
}

.green{
  color:#00FF00;
}

.blue{
  color:#0000FF;
}

.black{
  color:#666666;
}

jQuery:

var colors = ['red', 'blue', 'green', 'black'];
var start = 'red';
var i = 0;
$('.test').each(function() {
  var next = colors[($.inArray(start, colors) + i) % colors.length];
  $( this ).addClass(next);
  i++;
});

Each new heading will take next from array, and the colors in the array will start all over again when you get to the last one.

1 Comment

Tried it to no avail. Thanks anyhow!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.