How to apply CSS styling to dynamically generated list (within mCustomScrollbar container)?

1.6k views Asked by At

I'm dynamically generating a list from a MongoDB database using getJSON().

The HTML being generated is correct and the related CSS styles are also correct.

The <li>'s should have images as backgrounds, but they aren't being applied.

In Firebug, I hover over the image background URL for each <li> and the image is previewed so I can tell the path is correct, they are just not being displayed.

The solutions I have come across involve using listview('refresh') but that seems to be a jQuery Mobile solution and I am just using standard jQuery.

Another solution I have seen is to use addClass() to an element after the function has run, but the element already has the correct class applied in the HTML, the style is just not being displayed.

Is there a 'standard' way of re-applying CSS after a function has run, or another approach to ensure that CSS is applied to a dynamically generated list?

HTML

<ul class="my_ul_class"></ul>

jQuery (external js file)

$(document).ready(function() {
    loadListItems();
});

function loadListItems() {
    var href= "/url";
    $.getJSON("/path_to_python_script", {cid: href, format: 'json'}, function(results){
        $.each(results.my_key, function(k,v) {
            $("ul.my_ul_class").append("<li data-thing1=\"" + v + "\" class=\"prefix_" + v + "\"><ul class=\"nested\"><li class=\"hidden_li\"><p class=\"my_p_class\">text</p></li></ul></li>");
        });
    })
}

Generated HTML

<li class="prefix_1" data-thing1="1"><ul class="nested"><li class="hidden_li"><p class="my_p_class">text</p></li></ul></li>
1

There are 1 answers

0
user1063287 On BEST ANSWER

Solution

The solution involved modifying the placement of the mCustomScrollbar function which was applied to the div container of the <ul>.

jQuery (external js file)

// wrap mCustomScrollbar in a custom function
function listScrollbar() {
$("#my_ul_container").mCustomScrollbar({
horizontalScroll:true,
set_width: false,
set_height: false,
scrollInertia:550,
advanced:{
updateOnBrowserResize:true,
updateOnContentResize:true,
autoExpandHorizontalScroll:false,
autoScrollOnFocus:true
}
})
}

// dynamically generate <li>'s
function loadListItems() {
var href= "/url";
$.getJSON("/path_to_python_script", {cid: href, format: 'json'}, function(results){
$.each(results.my_key, function(k,v) {
$("ul.my_ul_class").append("<li data-thing1=\"" + v + "\" class=\"prefix_" + v + "\"><ul class=\"nested\"><li class=\"hidden_li\"><p class=\"my_p_class\">text</p></li></ul></li>");
});
// call the mCustomScrollbar function
listScrollbar()
})
}

// call loadListItems
$(document).ready(function() {
loadListItems();
});