2

I have these widgets with a sliding box inside. There are two widgets when the page is loaded, but you can add a widget and delete it again.

Inside the sliding box is a color picker, and on the starter widgets the color picker works properly, but in the added widgets the color picker doesn't work.

See this fiddle: http://jsfiddle.net/fULQZ/

I think the error is in the script for the color picker?

Here's the script for the color picker:

// Color picker
function updateBackground(color) {
    $(this).parents(".box_header").css("background", color.toHexString());
}


$(function() {


$(".flatPalette").spectrum({
    flat: true,
    showInput: true,
    showPaletteOnly: true,
    showPalette:true,
    maxPaletteSize: 10,
    palette: [
         ['#DDD','#9fd0d3', '#c9a9d1', '#e2a6a5', '#c2d2bd','#9fb2d1', '#dbba97', '#cbefe9', '#e6e8bf'],
        []
    ],
    change: updateBackground
});


});
Liam
  • 27,717
  • 28
  • 128
  • 190
DWTBC
  • 285
  • 5
  • 24

2 Answers2

1

extract your spectrum init in a dedicated function, change it a bit the selector to get all non init ones, and just call this function after the gridster.add_widget

function addSpectrum(){
    $(".flatPalette:empty").spectrum({ ... }); // :empty will get non init box
};

$('.addbox').on("click", function(){
    gridster.add_widget(' ... ', 2, 1);
    addSpectrum(); // add spectrum on the new box
});

addSpectrum(); // init spectrum on non dynamic box

http://jsfiddle.net/fULQZ/1/

r043v
  • 1,859
  • 1
  • 15
  • 25
  • Thank this is great, so now it's up to date – DWTBC Mar 06 '13 at 13:42
  • This approach is fine for smaller applications, but quickly gets messy with bigger ones. You have to always remember to initialize a component when you place it on the screen. Is there a better way? Some sort of automatic initialization if a class is detected? – Michael Yagudaev Jan 24 '14 at 20:32
  • http://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements – r043v Jan 24 '14 at 23:10
0

you need a "live" selector to match element added on runtime, check http://api.jquery.com/live/

Peminator
  • 783
  • 1
  • 9
  • 24
  • How and where would you go about, adding the "live" selector? on the `$(".flatPalette").spectrum({` or `function updateBackground(color) {` – DWTBC Mar 05 '13 at 11:50
  • well, as far as I know there is no 'elementCreated' event so you can either add the call to function to the same function where the widgets are created, or try the 'deprecated' live like this $(".flatPalette").live('mouseenter',function(){ $(this).spectrum();};) – Peminator Mar 05 '13 at 12:49
  • .live is deprecated and here it will call spectrum init at each click, you have luck than the plugin check is init before do his job – r043v Mar 05 '13 at 15:05