JQuery append() doesn't work from first call

Here's the code with methods

var view = {
drawColorBoxes: function (colors) {
    var colorField = $('.colors');

    if (colorField.length <= 0) {
        $('.thumbnails').after('<ul class="colors"></ul>');
    }
    $.each(colors, function (color) {
        console.log(color);
        colorField.append('<li class="colorbox"></li>');
    });
},

    markSelected: function (color_id) {

    },
};

Once page has been loaded method drawColorBoxes(colors) stars work normally: it creates <ul class="colors"></ul>but after that at $.each appending doesn't work.console.log shows data were recieved correctly. No exception appears, the method works fine when it is used later during the program.

Upvotes: 0

Views: 82

Answers (1)

Ahmed
Ahmed

Reputation: 656

The problem is when the element is not found colorField is empty so append will not work.

Try this

var view = {
drawColorBoxes: function (colors) {
    var colorField = $('.colors');

    if (colorField.length <= 0) {
        $('.thumbnails').after('<ul class="colors"></ul>');
        colorField = $('.colors'); // You need to reassign/initialize colorField.
    }
    $.each(colors, function (color) {
        console.log(color);
        colorField.append('<li class="colorbox"></li>');
    });
},

    markSelected: function (color_id) {

    },
};

Upvotes: 1

Related Questions