5

I am trying to change only the alpha channel in the background-color of a div element(using a slider). But I don't know how to do It. Here is my code:

$(function() {
    $( "#slider" ).slider({
        range: "min",
        value: 50,
        min: 0,
        max: 100,
        slide: function( event, ui ) {
            // While sliding, update the value in the alpha div element
            $('#idOfMyDiv').css('background', rgb(,,,ui.value) ); //I don't know what to do here
        }
    });
});
peterh
  • 11,875
  • 18
  • 85
  • 108
Rafael
  • 219
  • 2
  • 16

2 Answers2

5
  1. Fetch the current background color,
  2. Parse it into r,g,b
  3. Create a new rgba color string
  4. Change the background color to the new rgba color string.

Like this:

var newAlpha=0.50;

var bg=$('#idOfMyDiv').css('backgroundColor');

var a=bg.slice(4).split(',');

var newBg='rgba('+a[0]+','+parseInt(a[1])+','+parseInt(a[2])+','+newAlpha+')';

$('#idOfMyDiv').css('backgroundColor',newBg);

Example code and a Demo:

var newAlpha=0.50;
var bg=$('body').css('backgroundColor');
var a=bg.slice(4).split(',');
var newBg='rgba('+a[0]+','+parseInt(a[1])+','+parseInt(a[2])+','+newAlpha+')';
$('body').css('backgroundColor',newBg);
body{ background-color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
markE
  • 102,905
  • 11
  • 164
  • 176
  • 2
    This won't work if your current bg color is in rgba and not rgb. In this case you should `slice(5)` instead of `slice(4)` – Moradnejad May 10 '17 at 08:02
0

You can use the jQuery-Color extension

var element = $('#idOfMyDiv');
element.css('background-color', function(){ return $.Color( this, "backgroundColor" ).alpha(.9)})

$(function () {
    $("#slider").slider({
        range: "min",
        value: 50,
        min: 0,
        max: 100,
        slide: function (event, ui) {
            $('#idOfMyDiv').css('background', function () {
                return $.Color(this, "backgroundColor").alpha(ui.value / 100);
            })
        }
    });
});
#idOfMyDiv {
  background-color: red;
}
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/color/jquery.color.plus-names-2.1.2.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>

<div id="slider"></div>

<div id="idOfMyDiv">There is something here</div>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531