JavaScript API

Back

Loading concept...

๐ŸŽฎ Bootstrap JavaScript API: Your Remote Control for Websites!

Imagine this: You have a super cool toy robot. It has buttons, lights, and makes sounds. But what makes it actually move and do cool stuff? The remote control! Bootstrapโ€™s JavaScript API is exactly that โ€” the remote control for all those beautiful Bootstrap components like modals, dropdowns, and carousels!


๐ŸŒŸ The Big Picture

Think of Bootstrap like a LEGO set:

  • HTML = The LEGO bricks (structure)
  • CSS = The paint and decorations (looks pretty)
  • JavaScript API = The motors and gears that make things MOVE!

Without the JavaScript API, your modal is just a pretty picture. With it? ๐Ÿš€ It slides, it fades, it responds to your clicks!


๐Ÿ”ง JavaScript Initialization

What Is It?

When you wake up in the morning, you need to โ€œturn onโ€ before you can do anything, right? Initialization is waking up a Bootstrap component and telling it: โ€œHey, youโ€™re alive now! Start working!โ€

The Magic Words

There are two ways to wake up a Bootstrap component:

Way 1: Let Bootstrap Do It Automatically (Data Attributes)

Bootstrap looks at your HTML and thinks: โ€œOh! I see data-bs-toggle! Iโ€™ll handle this myself!โ€

<!-- Bootstrap wakes this up automatically! -->
<button data-bs-toggle="modal"
        data-bs-target="#myModal">
  Open Modal
</button>

Way 2: You Wake It Up with JavaScript

Sometimes you want to be the boss. You wake up the component yourself!

// Find the modal element
const myModal = document.getElementById('myModal');

// Wake it up! Create a new Modal instance
const modal = new bootstrap.Modal(myModal);

๐ŸŽฏ Real-Life Example

// Get the element
const toastEl = document.getElementById('myToast');

// Wake it up with options!
const toast = new bootstrap.Toast(toastEl, {
  delay: 3000,  // Show for 3 seconds
  autohide: true
});

// Now you can control it!
toast.show();

๐Ÿ’ก Pro Tip: Getting an Existing Instance

Already woke up a component before? Donโ€™t create a new one โ€” just find the existing one!

// Get the instance that's already awake
const modal = bootstrap.Modal.getInstance(myModal);

// Or get it, and if it doesn't exist, create it!
const modalOrNew = bootstrap.Modal
  .getOrCreateInstance(myModal);

๐ŸŽ‰ JavaScript Component Events

What Are Events?

Imagine your component is a dog. Events are the dog telling you things:

  • ๐Ÿ• โ€œIโ€™m about to bark!โ€ (before something happens)
  • ๐Ÿ• โ€œI just barked!โ€ (after something happened)

Bootstrap components talk to you through events!

The Two Types of Events

graph TD A["Event Happens"] --> B{Event Type?} B --> C["๐Ÿ”ฎ Before Event&lt;br/&gt;show.bs.modal&lt;br/&gt;hide.bs.modal"] B --> D["โœ… After Event&lt;br/&gt;shown.bs.modal&lt;br/&gt;hidden.bs.modal"] C --> E["You can STOP it!&lt;br/&gt;preventDefault"] D --> F["Already done!&lt;br/&gt;Just react to it"]

๐ŸŽฌ The Event Timeline

Event Name When It Fires Can You Stop It?
show.bs.modal Just BEFORE modal opens โœ… Yes!
shown.bs.modal AFTER modal is fully open โŒ No
hide.bs.modal Just BEFORE modal closes โœ… Yes!
hidden.bs.modal AFTER modal is fully closed โŒ No

๐Ÿ“ Listening for Events

const myModal = document.getElementById('myModal');

// Listen for the "about to show" event
myModal.addEventListener('show.bs.modal', (event) => {
  console.log('Modal is about to open!');
});

// Listen for the "finished showing" event
myModal.addEventListener('shown.bs.modal', (event) => {
  console.log('Modal is now fully open!');
  // Focus on an input inside the modal
  document.getElementById('myInput').focus();
});

๐Ÿ›‘ Stopping an Event

Want to stop a modal from opening? Say โ€œNO!โ€ with preventDefault()!

myModal.addEventListener('show.bs.modal', (event) => {
  // Check if user is not logged in
  if (!userIsLoggedIn) {
    event.preventDefault(); // STOP! Don't open!
    alert('Please log in first!');
  }
});

๐Ÿ“ฌ Finding Who Started It

The event carries information about what triggered it!

myModal.addEventListener('show.bs.modal', (event) => {
  // Who clicked the button that opened this?
  const button = event.relatedTarget;

  // Get data from that button
  const userId = button.getAttribute('data-bs-user');
  console.log('Opening modal for user:', userId);
});

๐ŸŽ›๏ธ JavaScript Component Methods

What Are Methods?

Methods are commands you give to your components. Like telling your robot: โ€œWalk forward! Turn left! Dance!โ€

Common Methods All Components Have

graph TD A["Bootstrap Component"] --> B["๐ŸŽฌ show"] A --> C["๐Ÿ™ˆ hide"] A --> D["๐Ÿ”„ toggle"] A --> E["๐Ÿ—‘๏ธ dispose"]
Method What It Does Example
show() Opens/reveals the component modal.show()
hide() Closes/hides the component modal.hide()
toggle() Open if closed, close if open dropdown.toggle()
dispose() Completely destroy it tooltip.dispose()

๐ŸŽฌ Using Methods

// Create the modal instance
const myModal = new bootstrap.Modal('#myModal');

// Open it!
myModal.show();

// Close it after 5 seconds
setTimeout(() => {
  myModal.hide();
}, 5000);

๐ŸŽ  Carousel-Specific Methods

Carousels have special commands for sliding:

const carousel = new bootstrap.Carousel('#myCarousel');

// Go to next slide
carousel.next();

// Go to previous slide
carousel.prev();

// Jump to slide number 3 (index 2)
carousel.to(2);

// Pause auto-sliding
carousel.pause();

// Start auto-sliding again
carousel.cycle();

๐Ÿงน Cleaning Up with dispose()

When youโ€™re done with a component, clean up after yourself!

const tooltip = new bootstrap.Tooltip('#myButton');

// Later, when you don't need it anymore...
tooltip.dispose();  // Gone! Memory freed!

โšก Static Methods

Some methods donโ€™t need an instance โ€” they work on the class itself!

// Get an existing modal instance
const modal = bootstrap.Modal.getInstance(element);

// Get or create if it doesn't exist
const modal = bootstrap.Modal.getOrCreateInstance(element);

๐Ÿท๏ธ Data Attributes API

What Are Data Attributes?

Data attributes are like sticky notes you put on your HTML elements. Bootstrap reads these notes and knows what to do โ€” no JavaScript writing needed!

They all start with data-bs- (the โ€œbsโ€ stands for Bootstrap!).

๐ŸŽฏ The Two Main Ones

graph TD A["data-bs-toggle"] --> B["What action?&lt;br/&gt;modal, dropdown, tab..."] C["data-bs-target"] --> D["Which element?&lt;br/&gt;&#35;myModal, .dropdown-menu..."] A --> E["Bootstrap knows&lt;br/&gt;WHAT to do"] C --> E

๐Ÿ“ Common Data Attributes

Attribute Purpose Example
data-bs-toggle What type of action "modal", "dropdown"
data-bs-target Which element to control "#myModal"
data-bs-dismiss What to close "modal", "alert"
data-bs-slide Carousel direction "next", "prev"

๐ŸŽช No JavaScript Needed!

Look how easy this is โ€” a working modal with ZERO JavaScript:

<!-- Button that opens modal -->
<button data-bs-toggle="modal"
        data-bs-target="#exampleModal">
  Open Modal
</button>

<!-- The Modal -->
<div class="modal" id="exampleModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5>Hello!</h5>
        <!-- Close button - also no JS! -->
        <button data-bs-dismiss="modal">ร—</button>
      </div>
      <div class="modal-body">
        <p>This works without any JavaScript!</p>
      </div>
    </div>
  </div>
</div>

๐ŸŽ›๏ธ Passing Options via Data Attributes

You can configure components right in the HTML!

<!-- Toast with custom options -->
<div class="toast"
     data-bs-autohide="false"
     data-bs-delay="10000">
  This toast won't auto-hide!
</div>

<!-- Carousel that doesn't loop -->
<div class="carousel"
     data-bs-wrap="false"
     data-bs-interval="3000">
  ...
</div>

๐Ÿ”„ Converting JavaScript Options to Data Attributes

Easy rule: Take the JavaScript option and add data-bs- prefix!

JavaScript Option Data Attribute
{ backdrop: 'static' } data-bs-backdrop="static"
{ keyboard: false } data-bs-keyboard="false"
{ delay: 5000 } data-bs-delay="5000"

๐Ÿšซ Disabling Data Attributes

Want Bootstrap to leave certain elements alone?

// Turn off ALL automatic initialization
// Add this BEFORE Bootstrap loads
window.addEventListener('load', () => {
  // Bootstrap won't auto-init anything
});

Or for specific elements:

<!-- This dropdown won't auto-initialize -->
<div class="dropdown" data-bs-toggle="false">
  ...
</div>

๐ŸŽ“ Putting It All Together

Hereโ€™s a complete example using everything we learned:

<!-- Button with data attributes -->
<button id="openBtn"
        data-bs-toggle="modal"
        data-bs-target="#superModal"
        data-bs-user-id="123">
  Open Super Modal
</button>

<!-- Modal with options via data attributes -->
<div class="modal"
     id="superModal"
     data-bs-backdrop="static"
     data-bs-keyboard="false">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 id="modalTitle">Welcome!</h5>
        <button data-bs-dismiss="modal">ร—</button>
      </div>
      <div class="modal-body">
        <p id="modalBody">Loading...</p>
      </div>
    </div>
  </div>
</div>
const modalEl = document.getElementById('superModal');

// Listen for events
modalEl.addEventListener('show.bs.modal', (event) => {
  // Get who triggered it
  const button = event.relatedTarget;
  const userId = button.getAttribute('data-bs-user-id');

  // Update modal content
  document.getElementById('modalTitle').textContent =
    `Hello, User ${userId}!`;
});

modalEl.addEventListener('shown.bs.modal', () => {
  console.log('Modal is ready!');
});

modalEl.addEventListener('hidden.bs.modal', () => {
  console.log('See you next time!');
});

// You can also control it with JavaScript
const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

// Maybe close it after 10 seconds
setTimeout(() => modal.hide(), 10000);

๐ŸŒˆ Quick Summary

Concept Think of it asโ€ฆ
Initialization Waking up a toy
Events The toy telling you what itโ€™s doing
Methods Commands you give the toy
Data Attributes Instruction sticky notes

๐Ÿš€ You Did It!

Now you know how to:

  • โœ… Wake up Bootstrap components with JavaScript
  • โœ… Listen to what theyโ€™re telling you through events
  • โœ… Command them with methods
  • โœ… Configure them without any JavaScript using data attributes

Youโ€™re now the master of the Bootstrap remote control! ๐ŸŽฎโœจ


๐Ÿ’ก Remember: Data attributes are great for simple stuff. JavaScript gives you superpowers when you need more control. Use both together for the best experience!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.