Search code examples
javascriptjquerycssspectrumjs

Attempting to get a css value with jquery


I am attempting to get a css value of a background. My attempt is failing and the correct value isn't being delivered. I have a spectrum.js color picker and no matter which color I choose rgba(0,0,0,0) is always chosen. When I look at the background in the console it displays it correctly in the DOM.

Does anybody see why this is failing?

<div class="container" id="outside-preview">
    <div class="container" id="inside-preview">
       <div id="image-square"></div>
    </div>
 </div>
$(".colorpicker").spectrum({
    color: "#FFF",
    showInput: true,
    className: "full-spectrum",
    showInitial: true,
    showPalette: true,
    showSelectionPalette: true,
    maxSelectionSize: 10,
    preferredFormat: "hex",
    localStorageKey: "spectrum.demo",
    change: function(color) {
        var eq =  $(this).index('.colorpicker');
        $('.container').eq(eq).css('background-color', color.toHexString())
    }
});

var color = $( "#outside-preview" ).css( "background-color" );
$("#result").html("That div is " + color + "");

Fiddle


Solution

  • You need to place the code which reads the CSS value in the change handler so that it updates the #result element after a selection is made. Your current code is only reading it on load.

    change: function(color) {
        var eq = $(this).index('.colorpicker');
        $('.container').eq(eq).css('background-color', color.toHexString())
    
        var color = $("#outside-preview").css("background-color");
        $("#result").html("That div is " + color);
    },
    

    Updated fiddle