Check background color or image

I am working on a blog theme that uses a mixture of great images and color colors when the author posts his post. I would like the script to do three things:

  • Check if there is a displayed image. If yes, use this.
  • If there is no color picture, is there a color? If yes, use this.
  • If none of these are checked, create a random color.

I have a JavaScript snippet that almost works and I think there might be a problem with the logic I am using in the statement if

.

Script

$(".post").each(function randomColor() {
        var bgCol = $(".post").css('backgroundColor');
        if ( bgCol != "rgb(0,0,0)" || (bgCol.attr('style').indexOf('image') !== -1 )) {
          var color = "#"+(Math.random()*0xFFFFFF<<0).toString(16);
          $(this).css("background-color", color)
        }
        else { return }
      });

      

I have installed a jsFiddle to demonstrate the problem . It preserves the images, but overrides the color of the tag if it is set.

Any thoughts on how I can improve the loop if

?

I have a demo (very rare) blog theme so you can see what I'm going to do.

+3


source to share


2 answers


jsBin demo

I would look at the computed styles:

$(".post").each(function() {
  var cs = window.getComputedStyle(this);
  if (cs.backgroundImage==="none" &&
      cs.backgroundColor==="transparent" ||
      /0\)$/.test(cs.backgroundColor) ) {
    var color = "hsl("+ ~~(Math.random()*360) +",60%,70%)";     
    $(this).css("background-color", color);   
  }
});

      



This line /0\)$/.test(cs.backgroundColor)

just checks if the value ends up with a rgba

0-transparent opacity 0)

(Webkit returns rgba (0, 0, 0, 0) instead of "transparent" which is basically the same).

Using hsl()

Hue, Saturation, Lightness (instead of hex #

) will give you more control over the randomly generated color intensity (so you can best approach the overall concept of lightness and feel on a website).

+2


source


$(".post").each(function randomColor() {
        var bgCol = $(".post").css('backgroundColor');
        console.log(bgCol);
        if ( bgCol == "rgba(0, 0, 0, 0)") {
          var color = "#"+(Math.random()*0xFFFFFF<<0).toString(16);
          $(this).css("background-color", color)
        }
        else { return }
      });

      



Here is the code, since all the changes applied by the css you just need to search for the element with no background and generate a random color.

0


source







All Articles