0
function createList() {
var list = '';
var listID;
$.each(obj_JSON.colors, function(index, value) {
    listID = "clr_" + index;
    list = list + "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
    clrList.html(list);
    updateListColours(listID);
});

}

function updateListColours(x) {
    $('#' + x).css({"background-color":"rgb(255, 0, 0)", "height":"25px", "width":"25px"});
}

When I watch it get created. The first div gets the style applied to it. Then the second gets created and the style is wiped from the first div and applied to the second and it goes on until the list is complete...

Why is this happening and how can I apply the style to each div? Expecting answer that shows i've done something really stupid as usual

2
  • return the updateListColurs(listID) Commented Apr 11, 2014 at 9:50
  • Ensure that x is the correct id selector value. Commented Apr 11, 2014 at 9:52

2 Answers 2

3

Because this line clrList.html(list);, you are removing the previous element then add new created.

Instead, do it with:

$.each(obj_JSON.colors, function(index, value) {
    listID = "clr_" + index;
    list = "<div id=" + listID + " alt='" + obj_JSON.colors[index].name + "'></div>"
    clrList.append(list);
    updateListColours(listID);
});
Sign up to request clarification or add additional context in comments.

1 Comment

ahhh I see! Thank you! I will run the css apply to all of the list after the creation is completed. Haha I knew it was stupid afterall. Thank you! (will tick when timer goes).
0

There's a much easier solution:

function createList() {
    $.each(obj_JSON.colors, function() {
        var d = document.createElement('div');
        d.setAttribute("alt",this.name);
        d.className = "listcolour";
        clrList.appendChild(d);
        // ^ assumes `clrList` is a DOM node, not a jQuery object
    });
}

And CSS:

.listcolour {
    width: 25px;
    height: 25px;
    background-color: #f00;
}

2 Comments

I couldn't use this method because the list items will have different colours - they are all red at the moment because I was just trying to get it to work at a more basic level. But thanks for the input!
Well, you can use the class for the size, then use d.style.backgroundColor = 'whatever'; as well. The point is, sometimes Vanilla JS is a lot simpler ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.