Randy Thomas
Randy Thomas

Reputation: 343

Change DIV Color Using Color Picker

I am banging my head against the wall here. This code has no reason not to work but it does not.

I want the user to be able to pick a color using jscolor (I don't want to use type="color" because it may not work for some of my users). Once they pick a color it needs to change the div background-color.

When I use type="color" in the input, it works. But it will not work with the jscolor script.

My Code:

Javascript:

<script type='text/javascript'>
    $(window).load(function () {
        $('#bgcolor').on('change', function (e) {
            var optionSelected = $("option:selected", this);
            var valueSelected = this.value;
            $(".background").css("background-color", valueSelected);
        });
    });
</script>

HTML: (input)

<input style="width:100px;" class="jscolor {width:243, height:150, position:'right',
borderColor:'#FFF', insetColor:'#FFF', backgroundColor:'#666'}" id="bgcolor" name="bgcolor" value="2e2e2e" />

HTML: (the div it should change)

 <div id="background" class="background" style="position: absolute; 
       background-color: #2e2e2e; width: 247px; height: 335px; 
       overflow: scroll; overflow-x: hidden;">

Upvotes: 1

Views: 4995

Answers (2)

AlexW
AlexW

Reputation: 3399

  1. Imported the jscolor.js from: http://jscolor.com
  2. Seperated the data from class name to an attribute data-jscolor, based on the demo.

Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="jscolor.js"></script>
<script>
    $(document).ready(function(){

        $('#bgcolor').on('change', function (e) {

            var optionSelected = $("option:selected", this);
            var valueSelected = this.value;
            $(".background").css("background-color", valueSelected);
        });
    });
</script>
<input style="width:100px;" class="jscolor" data-jscolor="{width:243, height:150, position:'right',
borderColor:'#FFF', insetColor:'#FFF', backgroundColor:'#666'}" id="bgcolor" name="bgcolor" value="2e2e2e" />

<div id="background" class="background" style="position: absolute; background-color: #2e2e2e; width: 247px; height: 335px; overflow: scroll; overflow-x: hidden;"></div>

Upvotes: 0

David R
David R

Reputation: 15637

You have three issues in your code.

1) > is coming at the end of your script which you should remove.

2) You are trying to use a class selector to select your background div where you should use an ID selector as $("#background")

3) You should prefix an # infront of your valueSelected value. (It should be var valueSelected = '#' +this.value;)

Working DEMO: https://jsfiddle.net/7g7Lh2L2/2/

Hope this helps!

Upvotes: 3

Related Questions