Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Bootstrap notified by DOM changes?

A lot of Bootstrap plugins are immediately working if some data-*="xzy" attributes are added (interactively).

E.g. just add data-toggle="collapse" to an anchor tag and Bootstrap Collapse is present, see demo https://jsfiddle.net/4n5zrkpb/.

I want to know:

  • What's the technology behind? (As far as I know they don't listen to mutation events and don't use MutationObserver.)
  • Can I use it on my own ;-)

UPDATE: I don't want Event binding on dynamically created elements?. I originally wanted to be updated when new elements has been created dynamically! But the Bootstrap way is far more easy and backward compatible: Notify only if some user interaction (e.g listen to all click events) took place.

like image 351
Marcel Avatar asked Dec 03 '25 15:12

Marcel


2 Answers

It's basically an observing of a click element on the document, filtered by an attribute selector with jQuery.

It's like this

jQuery(document).on('click', '[data-toggle="collapse"]', doTheToggleMagic) 

That means, every click on the document is reacted upon, but only if the source of the click event was an element with the attribute of data-toggle with a value of collapse.

So to answer your question in the title: Wordpress is not notified of DOM changes at all. Because it doesn't need to. It only reacts, if the user interacts.

like image 153
yunzen Avatar answered Dec 05 '25 05:12

yunzen


TL;DR

It uses the jQuery .on() function to attach to any element based on the [data-*] selector

Code sample

If you look into the source code (available on their website) https://getbootstrap.com/docs/4.2/getting-started/download/#source-files

In the boostrap.js:1468 file you have the following chunk of code:

$(document).on(Event$3.CLICK_DATA_API, Selector$3.DATA_TOGGLE, function (event) {
  // preventDefault only for <a> elements (which change the URL) not inside the collapsible element
  if (event.currentTarget.tagName === 'A') {
    event.preventDefault();
  }

  var $trigger = $(this);
  var selector = Util.getSelectorFromElement(this);
  var selectors = [].slice.call(document.querySelectorAll(selector));
  $(selectors).each(function () {
    var $target = $(this);
    var data = $target.data(DATA_KEY$3);
    var config = data ? 'toggle' : $trigger.data();

    Collapse._jQueryInterface.call($target, config);
  });
});

This is only an example, but as you can see the event is attached to the document element and attaches to any dinamically loaded element using jQuery on() http://api.jquery.com/on/

like image 28
VladNeacsu Avatar answered Dec 05 '25 05:12

VladNeacsu