Question

I'm new to Javascript and JQuery so please be patient. I want to make a box-shadow that changes color when using a color picker. For this I'm using Jscolor.js. It's my understanding that I need to use a Onchange function and use +this.color to select the current color.

However I can't seem to get the code to work, I've tried reading everywhere but there isn't much information on the subject I need. I have created a JsFiddle as a example.

Thank you very much for the help in advance.

CODE:

JAVASCRIPT:

$(document).ready(function(){ 
    $('#content').css('boxShadow', '+this.color inset 0 200px 400px -200px');
    $('#content').css('boxShadowColor', '+this.color'); 
});

HTML:

<div id="content">
    <p>
         <input class="color" onchange="$('#content').css('boxShadow','+this.color');" />
         <h1> This is a example.</h1>
</div> 
</div>

CSS:

.content {   
    -webkit-box-shadow: inset 0 200px 400px -200px #000);
    -moz-box-shadow: inset 0 200px 400px -200px #000);
    box-shadow: inset 0 200px 400px -200px #000; 
}
Était-ce utile?

La solution

FIDDLE

HTML

<div id="content">
    <p>
        <input class="color" onchange="addNewBoxShadowStylesToHead('#frontcontent', '#'+this.color);" />
        <h1> This is a example.</h1>
    </p>
</div>

<div id="frontcontent">This div will have the effect</div>

JS

var head = document.head || document.getElementsByTagName('head')[0];

function addNewBoxShadowStylesToHead(selector,color) {
    var css = selector + '{-webkit-box-shadow: inset 0 200px 400px -200px ' +color+ ';' +
        '-moz-box-shadow: inset 0 200px 400px -200px ' + color + ';'+
        'box-shadow: inset 0 200px 400px -200px ' + color + '; }',
        style = document.createElement('style');

    style.type = 'text/css';
    if (style.styleSheet){
        style.styleSheet.cssText = css;
    } else {
        style.appendChild(document.createTextNode(css));
    }

    head.appendChild(style);
}

OR Simpler JS

function applyboxshadow(selector, color) {
    $(selector).css({
         '-webkit-box-shadow' : 'inset 0 200px 400px -200px ' + color,
        '-moz-box-shadow': 'inset 0 200px 400px -200px '+ color,
        'box-shadow': 'inset 0 200px 400px -200px '+ color
    });
}

call it like so

<input class="color" onchange="applyboxshadow('#frontcontent', '#'+this.color);" />
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top