Jon
Jon

Reputation: 8511

Check When New Element Is Created

I have div.scrollContainer where I insert a bunch of items. When the page loads, I run mCustomScrollbar jQuery plugin which will take the items inside div.scrollContainer and wrap its own classes/css/js around it to create the custom scroll bar.

When the page loads, I go through my own library which outputs some more items for me to inject into the scroll bar. I am currently targeting/appending them to the custom classes mCustomScrollbar creates. The problem, however, is that sometimes my library outputs the items before mCustomScrollbar has created its classes. As a result, the items from the library can never be placed inside the correct element because it doesn't exist.

I have thought about appending the items from the library to div.scrollContainer, but then I run into the issue of what if mCustomScrollbar has created its classes before the items are appended.

All in all, I am wondering if there is a way to detect when a new element is created in the DOM. I have looked into this other thread where it was suggested to use the livequery plugin. I'm wondering if there is a solution that does not require an additional plugin.

Upvotes: 2

Views: 906

Answers (2)

CatalinBerta
CatalinBerta

Reputation: 1724

Use the updateOnContentResize: true setting and it will check every few milliseconds for new content. When you launch the plugin, also add these among your other settings: $(selector).mCustomScrollbar({ advanced:{ updateOnContentResize: true } });

However! Personally I am against useless DOM traversing every few milliseconds, I recommend you use its native update method. Find a way to know when you add more content to your scrollbar markup and just run this whenever needed: $(selector).mCustomScrollbar("update");

P.S. read its documentation, quite many and useful settings/methods.

Hope this helps :)

Upvotes: 0

scumah
scumah

Reputation: 6383

You can call .mCustomScrollbar() after inserting the last items, so you are positively sure that the items are really inserted:

$(".your-container").append($(".your-items"));
$("div.scrollContainer").mCustomScrollbar();

Upvotes: 1

Related Questions