2

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.

Community
  • 1
  • 1
Jon
  • 8,205
  • 25
  • 87
  • 146
  • Can you insert those later items before calling `mCustomScrollbar` or you need those mCustomScrollbar's classes to append them? If you can insert them first you can try calling `$("div.scrollContainer").mCustomScrollbar();` right after your items are inserted (using the `.append` callback, for example). – scumah Nov 29 '12 at 21:06
  • @scumah That works. Can you post it as an answer so I can accept? – Jon Nov 29 '12 at 22:52
  • Sure @icu222much, there you go, I'm glad it helped. And btw, I mentioned it in my previous comment, but there's no such thing as the .append callback :/ In fact, there's no need for one. Sorry for that :) – scumah Nov 29 '12 at 23:34

2 Answers2

1

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();
scumah
  • 6,273
  • 2
  • 29
  • 44
0

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 :)

CatalinBerta
  • 1,604
  • 20
  • 20