I am trying to change the colors of an svg linearGradient using jquery but my code only works on Chrome.
Can any one help me out here to make it cross browser?
$(document).ready(function() {
$(".input-holder:first .form-control").focusout(function(e) {
var colorValue = $(this).val();
var s = "#" + colorValue;
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(s);
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")";
$(this).next(".color-rgba").html(rgb);
var getColor = $("lineargradient#grad1 stop:first").css('stop-color');
//alert(getColor);
$("lineargradient#grad1 stop:first").css('stopColor',rgb);
});
$(".input-holder:eq(1) .form-control").focusout(function(e) {
var colorValue = $(this).val();
var s = "#" + colorValue;
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(s);
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")";
$(this).next(".color-rgba").html(rgb);
$("lineargradient#grad1 stop:eq(1)").css('stopColor',rgb);
//$("lineargradient#grad1 stop:eq(1)").css('-moz-stop-color',rgb);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="input-holder">
<label>First Gradient Color</label>
<input type="text" class="form-control">
<em class="color-rgba"></em>
</div>
<div class="input-holder">
<label>Second Gradient Color</label>
<input type="text" class="form-control">
<em class="color-rgba"></em>
</div>
<svg height="150" width="400">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="70%" y2="0%">
<stop id="stp1" class="stop1" offset="50%" style="" />
<stop offset="100%" style="stop-color:rgb(13,93,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
Sorry, your browser does not support inline SVG.
</svg>
</div>
SVG is case sensitive so its linearGradient and not lineargradient. In other words you should need this:
Unfortunately this won't work on Chrome as Chrome incorrectly requires element names to be lowercased.
The usual workaround for Chrome is to give all the linearGradientElements a class of linearGradient and then select by class rather than by element name. In your case since you've given the gradient an id, you could just use that.