bflora2
bflora2

Reputation: 753

Possible to "listen" to a CSS value for a DOM element and tell another DOM element to match it?

I'm trying to hack Drupal's colorpicker module so that as my user drags it around picking colors, he sees colors changing on the web site's in real-time.

Right now the colorpicker's js changes the color of the picker widget in real-time.

I want to hack the js so that the color of the picker widget AND a specific DOM element change background colors at once.

Is there a way I can write some code that "listens" to the background-color setting of the colorpicker input and then changes the background-color of ?

Here's the code where Drupal is applying settings from the colorpicker widget to its input:

Drupal.behaviors.colorpicker = function(context) {  
$("input.colorpicker_textfield:not(.colorpicker-processed)", context).each(function() {
var index = $('body').find('input.colorpicker_textfield').index($(this));
Drupal.colorpickers[index] = new Drupal.colorpicker($(this).addClass('colorpicker-processed'));
Drupal.colorpickers[index].init();
});

What can I add to this to tell it to "listen" to the background color of "input.colorpicker_textfield" and then set that value to "body" in real time as it changes?

Upvotes: 3

Views: 270

Answers (2)

typeof
typeof

Reputation: 5922

Similar to Cole's answer with some improvements (assuming '#' is not included by the colorpicker):

$('input.colorpicker_textfield').live('change', function() {
    var color = this.value;
    if(color.search((/^[A-Fa-f0-9]{6}/) != -1) {
        body.style.backgroundColor = '#'+this.value;
    }
});
  • Uses more specific selector
  • uses the 'live' event handling method, ensuring the handler will be attached to any dynamically created colorpickers
  • It will not change the background color if the input is not a hex value
  • It uses the style attribute directly instead of wrapping in the jQuery object.

Upvotes: 0

Cole
Cole

Reputation: 740

Try using change() to apply it to the bg.

$("input").change( function () {
   //var below would obviously have to be correctly formatted.
   var newColor$(this).val();
   $(body).css({background-color: newColor});
});

Upvotes: 1

Related Questions