Placeholder
Placeholder

Reputation: 689

Making every a href on my site a different color

Currently, I am doing this with just static CSS using something that looks like the code displayed below.

#main-content > article.mh-loop-item.clearfix.post-95.post.type-post.status-publish.format-standard.has-post-thumbnail.hentry.category-singles.tag-kxngg-jxnes-italy > div > header > h3 > a {
color: blue;
}
#main-content > article.mh-loop-item.clearfix.post-93.post.type-post.status-publish.format-standard.has-post-thumbnail.hentry.category-singles.tag-aquil-eddie-guerrero > div > header > h3 > a {
color: red;
}

And for each post ID it generates a different color for that songs title to appear as, how ever I'm trying to do something a bit more advanced with Javascript or something that when ever there's an a href with a certain class it generates a random color for that link to appear as.

Upvotes: 3

Views: 127

Answers (3)

RizkiDPrast
RizkiDPrast

Reputation: 1725

something like this work, please give it a try:

/*I just hard coded everything*/
var yourClass = "article",
  hs = Array.from(document.querySelectorAll('a.' + yourClass)),
  colors = ['blue', 'red', 'green', 'purple', 'black', 'blue', 'yellow', 'lime'];

hs.forEach(function(elm) {
  elm.style.color = colors[Math.floor(Math.random() * colors.length)];
})
<a href="#"> normal </a>

<a class="article" href="#"> title1 </a>
<a class="article" href="#"> title2 </a>
<a class="article" href="#"> title3 </a>
<a class="article" href="#"> title4 </a>

Upvotes: 4

Sumit Surana
Sumit Surana

Reputation: 1584

It can be achieved by jquery as below

$(document).ready(function(){
  
  $('body a').each(function(){
    var color = 'rgb(' + randomNumber() + ',' + randomNumber() + ',' + randomNumber() + ')';
    $(this).css("color", color);
  });
  
  function randomNumber(){
    return Math.floor(256*Math.random());
  }
  
});
<a href="javascrip:void(0)">First link</a>
<a href="javascrip:void(0)">Second link</a>
<a href="javascrip:void(0)">Third link</a>
<a href="javascrip:void(0)">Fourth link</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Upvotes: 7

kjonsson
kjonsson

Reputation: 2799

Ok if you really want to do this (don't see why but I like it :-) ). Then I'll show you a way. I'm gonna use jquery for this but feel free to improvise.

Create or edit your javascript file. And follow along (I'm assuming that your post titles have class called postTitle)

$('.postTitle').each(function () {
    var red = Math.floor(Math.random() * 256);
    var green = Math.floor(Math.random() * 256);
    var blue = Math.floor(Math.random() * 256);
    $( this ).css("color", "rgb(" + red + "," + green + "," + blue + ")");
})

Upvotes: 2

Related Questions