views:

75

answers:

3

Hi

I need to add a color picker to some input elements. I'm using

$(".element").colorPicker(){ ... }

This works perfectly. The problem is that the page has a AJAX form, which - when submitted - will overwrite the previous form with a new one (new input fields etc). After that the colorPicker stops working.

So how can I fire that function to the newly created inputs too?

+1  A: 

Just reattach the invocation in the ajax callback, since I don't believe there is a reliable event you can use to .live or .delegate it, without revealing more information.

meder
so I add the `<script> $(".element) ... </script>` part again in the ajax response?
Alex
In the ajax `success` function, reinvoke `.colorPicker`.
meder
A: 

I believe this might work:

$(".element").live('click focus', function () {
    var $this = $(this);
    if (!$this.data('hasColorPicker')) {
        $this.colorPicker({ /* ... */ }).data('hasColorPicker', true);
        $this.click(); // trigger the color picker - assuming it binds itself to the click event
    }
});
CD Sanchez
A: 

What meder says is good, but also, if you are creating the new elements by copying existing ones, consider using $.clone(true) to make your copies and it will carry over existing event bindings too.

mkoistinen