What mechanism does Bootstrap use to detect changes in the DOM?

Many Bootstrap plugins become functional simply by adding certain data-*="xzy" attributes to elements (in real-time).

For example, just include data-toggle="collapse" in an anchor tag and Bootstrap Collapse will work immediately. Check out the demo https://jsfiddle.net/4n5zrkpb/.

I am curious about:

  • What technology is used behind this functionality? (I heard they do not rely on mutation events or use MutationObserver.)
  • Can I implement it myself ;-)

UPDATE: I do not want to deal with Event binding on dynamically created elements?. Originally, my goal was to know when new elements were dynamically created! However, the Bootstrap method seems more convenient and compatible: It only notifies if there is some user interaction (such as listening to all click events).

Answer №1

This code snippet is essentially setting up an event listener in jQuery to respond to clicks on specific elements in the document that have a certain attribute.

It looks like this:

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

In simpler terms, this means that any click on the document triggers a reaction, but only if the click originated from an element with the data-toggle attribute set to collapse.

To clarify the question posed in the title: Wordpress does not actively monitor DOM changes because it doesn't need to. It only responds when user interactions occur.

Answer №2

A brief summary

The usage of the jQuery method .on() is demonstrated in this code snippet, allowing for attachment to elements based on the [data-*] selector.

Highlighted code snippet

For those interested in exploring further, the source code can be found on their official website at https://getbootstrap.com/docs/4.2/getting-started/download/#source-files

Within the file boostrap.js:1468, there exists the following segment 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);
  });
});

While this serves as an illustration, it effectively showcases how the event is linked to the document element and adapts to any dynamically loaded element utilizing jQuery's on() method. Learn more about http://api.jquery.com/on/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My local requests are being blocked by both Chrome and Firefox

Recently, I've been experimenting with local flash development and trying to inject my swf file into a website served by my test server. To enable loading of local resources in Chrome, I set --disable-web-security. In FireFox, I made the following a ...

The navigation bar initially fills the width of the screen, but does not adjust to match the width of the table when scrolling

I've spent the last 2 hours playing around with CSS, using width:100% and width:100vw, but nothing seems to be working. Currently, the navigation bar fits perfectly across the screen on desktop browsers, so there doesn't seem to be an issue ther ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

Tips for implementing JS function in Angular for a Collapsible Sidebar in your component.ts file

I am attempting to collapse a pre-existing Sidebar within an Angular project. The Sidebar is currently set up in the app.component.html file, but I want to transform it into its own component. My goal is to incorporate the following JS function into the s ...

Hover-enabled dropdown menu in React-Bootstrap

While developing my first react-bootstrap website, I encountered an issue with the dropdown in the navbar not functioning properly upon hover. I have attempted to find a solution by experimenting with CSS code. I even created a demo which can be viewed he ...

Enhancing traditional functions with Javascript annotations or decorators

Currently, I am in the process of developing a Next.js application, where I have defined an API as shown below: export default function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method === 'GET') { fn1Get(req, res); } e ...

Discovering a specific element using jQuery

I am trying to work with a div structure like this: <div class="country"> <div class="cty_popover"> <p>TITLE</p> <ul> <li>NAME 1</li> <li>NAME 2</li> ...

Tips on adding TypeScript annotations to an already existing global function

I'm contemplating enhancing an existing project by incorporating TypeScript type annotations. Struggling to supply an external declaration file for a straightforward example: app.ts: /// <reference path="types.d.ts"/> function welcome (person ...

Achieve multiple returns of a function by employing .fadeOut() iteratively instead of just once

I'm not sure if it's supposed to behave this way, but I believe it is... Initially, I thought there might be an issue with my entire script so I created a new file on localhost to test just the fadeOut(); function. To my surprise, the function ...

Tips for setting a select list to have no elements pre-selected when using the jQuery bsmSelect plugin

Looking for a way to have the jQuery bsmSelect plugin start with nothing selected by default? This handy plugin makes it easy for users to choose multiple options from a dropdown list, but you need it to begin blank. Any suggestions on how to achieve this? ...

AngularJS: Enabling unidirectional binding for select option to model

Utilizing a dropdown to display client names. Users have the ability to choose an existing client, which will then update the scope property: Controller Setting up the initial selection. if($scope.clients.length > 0) $scope.existingClient = $scope.cl ...

Loading fonts in React Native without using Expo

Utilizing expo-font, we have the capability to render fonts asynchronously during the app loading process. Here is a demonstration. Similarly, let's explore how we can achieve font rendering without relying on expo. import {AppLoading} from ' ...

What is the best way to locate all mesh faces that are being lit up by a SpotLight

I am working with a THREE.Mesh that consists of a THREE.BufferGeometry containing "position" and "normal" THREE.BufferAttributes. This mesh is being lit by a THREE.SpotLight (which is a cone-shaped light source). Is there a method to ...

Angular Commandments: Understanding the Directives

Within my code, there is a specific directive view that I am utilizing: <div class="busy-indicator angular-animate" ng-show="busy"></div> <div class="breadcrumblist" ng-class="atTopLevel ? ['at-top-level'] : null"> <div ...

Using the `find()` method in a loop of Mongoose iterate

Searching for documents based on conditions stored in an array can be quite useful. Take this example: subscriptions=[ {teacher: 'john', student:'david' ,course:'math'}, {teacher: 'john', student:'david' , ...

Problem with incorporating responsive gifs

I'm new to CSS and I'm trying to incorporate an animated GIF as a smartphone screen using Bootstrap to ensure responsiveness. I've managed to get it working for larger and medium screens, but the issue arises when resizing for smaller displa ...

Utilizing a Custom Validator to Compare Two Values in a Dynamic FormArray in Angular 7

Within the "additionalForm" group, there is a formArray named "validations" that dynamically binds values to the validtionsField array. The validtionsField array contains three objects with two values that need to be compared: Min-length and Max-Length. F ...

Unusual Behavior Observed in JavaScript Map Reduce

var t = [-12, 57, 22, 12, -120, -3]; t.map(Math.abs).reduce(function(current, previousResult) { return Math.min(current, previousResult); }); // returns 3 t.map(Math.abs).reduce(Math.min); // returns NaN I'm puzzled as to why the second variant ...

The placement of all buttons must be at the bottom of every card

I'm looking for a way to align the buttons Get LenoxBot and Dashboard at the bottom of each card, as they currently have varying heights. https://i.sstatic.net/qVXZI.png This is the code I'm currently using: <div class="card mt-3 serverscar ...

Using jQuery to assess the values of all visible textboxes

Coming up with a suitable title for this question might be more challenging than the actual question itself. I've set up an error handler on one of my pages for posting to the database. It validates whether the input fields are empty and prevents exe ...