Reddy
Reddy

Reputation: 1497

How to get first and last hex code of gradient colors using jQuery

I want to get first (#00ffff) and last (#ff00ff) color of hex codes by using jquery...

Tried below without luck :(

jsFiddle

var myFirstColor = $('.gradient').css('background').split('linear-gradient')[0];
var mySecondColor = $('.gradient').css('background').split('linear-gradient')[1];

$('#firstColor').text(myFirstColor);
$('#secondColor').text(mySecondColor);
.gradient{background: linear-gradient(90deg, #00ffff 0%, #ff00ff 100%);}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 <div class="gradient">Gradient colors</div>
<div>First color : <span id="firstColor"></span></div>
<div>Second color : <span id="secondColor"></span></div>

Upvotes: 0

Views: 227

Answers (1)

mplungjan
mplungjan

Reputation: 177702

Try some regular expressions and number to hex

The computed values are in rgb format

I get the background-image instead of background since FX does not return expected string in background

Added support for RGBA but I decided to ignore transparency

const num2hex = num => ("0" + num.toString(16)).slice(-2)
const rgb2hex = rgb => "#" + rgb.split(",").slice(0,3).map(str => num2hex(+str)).join(""); // ignore tranparency
const getColors = selector => {
  const computed = $(selector).css('background-image');
  // console.log(computed)
  const [myFirstColor, mySecondColor] = computed.matchAll(/, rgb(?:a)?\((.+?)\)/g)
  return [rgb2hex(myFirstColor[1]),rgb2hex(mySecondColor[1])]
}
let colors = getColors(".gradient1")
$('#firstColor1').text(colors[0]).css({"background-color":colors[0]});
$('#secondColor1').text(colors[1]).css({"background-color":colors[1]});
colors = getColors(".gradient2")
$('#firstColor2').text(colors[0]).css({"background-color":colors[0]});
$('#secondColor2').text(colors[1]).css({"background-color":colors[1]});
.gradient1 {
  background-image: linear-gradient(90deg, #00ffff 0%, #ff00ff 100%);
}

.gradient2 {
  background-image:  linear-gradient(to right, rgba(255,0,0,0), rgba(0,255,0,1));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="gradient1">Gradient colors</div>

<h2>Gradient1</h2>
<div>First color : <span id="firstColor1"></span></div>
<div>Second color : <span id="secondColor1"></span></div>
<hr>
<div class="gradient2">Gradient colors</div>
<h2>Gradient2</h2>
<div>First color : <span id="firstColor2"></span></div>
<div>Second color : <span id="secondColor2"></span></div>

Upvotes: 1

Related Questions