A
A
Alexey Korolev2022-01-10 14:48:09
JavaScript
Alexey Korolev, 2022-01-10 14:48:09

How to make multiple links to one Toasts in Bootstrap?

I need to display a single message when certain links on a website are clicked. However, only the first button works from such a structure. How to make all buttons link to one Toasts?

<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>
<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>
<button type="button" class="btn btn-primary" id="liveToastBtn">Show live toast</button>

<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="..." class="rounded me-2" alt="...">
      <strong class="me-auto">Bootstrap</strong>
      <small>11 mins ago</small>
      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
    </div>
    <div class="toast-body">
      Hello, world! This is a toast message.
    </div>
  </div>
</div>


var toastTrigger = document.getElementById('liveToastBtn')
var toastLiveExample = document.getElementById('liveToast')
if (toastTrigger) {
  toastTrigger.addEventListener('click', function () {
    var toast = new bootstrap.Toast(toastLiveExample)

    toast.show()
  })
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2022-01-10
@SergeiB

The identifier on the site must have a unique name, so id="liveToastBtn" x3 is already wrong. Replace id with a class like js-toast-trigger. Next, hang a handler on each element in the loop (and there is nothing to create a new instance of the pop-up window with each click, so let's take it outside):

const toastTriggers = document.querySelectorAll('.js-toast-trigger');
const toastLiveExample = document.getElementById('liveToast');
const toast = new bootstrap.Toast(toastLiveExample);

if (toastTriggers.length) {
  toastTriggers.forEach(function(trigger) {
    trigger.addEventListener('click', function() {
      toast.show();
    });
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question