user2738640
user2738640

Reputation: 1227

jQuery code works only after 2nd click

I am using a jQuery plugin which has following configuration to run:

$('#colorSelector').ColorPicker({

});

However, I need to add this to a div dynamically added with the jQuery, therefore I am using following:

$(document).on('click', '#colorSelector', function(){

    $(this).ColorPicker({

    });

});

With the above method, it works but only after clicking couple of times. It does not work on the first click. How can I make it work on the first click.

Demo: http://jsfiddle.net/G8yBX/

Upvotes: 0

Views: 136

Answers (4)

vol7ron
vol7ron

Reputation: 42099

Only call it once; no need to be nested in a document event.

$('#colorSelector').ColorPicker({
    color: '#0000ff',
    onShow: function(colpkr) {
        $(colpkr).fadeIn(200);
        return false;
    },
    onHide: function(colpkr) {
        $(colpkr).fadeOut(200);
        return false;
    },
    onChange: function(hsb, hex, rgb) {
        $('#colorSelector div').css('backgroundColor', '#' + hex);
        $('#colorSelector input').val('#' + hex);
    }
});

You can bind it in the event that adds the element, if that's your goal.

Upvotes: 1

Kevin B
Kevin B

Reputation: 95030

If you want to use delegation for this, you'll have to make sure you aren't re-initializing it on each click by using an additional class, then at the end you'll want to re-trigger the click event and prevent this one from completing.

$(document).on('click', '#colorSelector:not(.cp)', function(){

    $(this).addClass('cp').ColorPicker({
        color: '#0000ff',
        onShow: function(colpkr) {
            $(colpkr).fadeIn(200);
            return false;
        },
        onHide: function(colpkr) {
            $(colpkr).fadeOut(200);
            return false;
        },
        onChange: function(hsb, hex, rgb) {
            $('#colorSelector div').css('backgroundColor', '#' + hex);
            $('#colorSelector input').val('#' + hex);
        }
    }).click();
    return false; 

});

http://jsfiddle.net/Tentonaxe/G8yBX/12/

I would instead use the success callback of whatever is generating the colorpicker.

Upvotes: 1

lxe
lxe

Reputation: 7579

Seems like you'll have to initialize it first, and then call show():

http://jsfiddle.net/G8yBX/6/

Upvotes: -1

tymeJV
tymeJV

Reputation: 104775

Once you dynamically add the div, call ColorPicker on it immediately after, else you need to click once to activate the code (as you can see in your demo).

Upvotes: 2

Related Questions