isherwood
isherwood

Reputation: 61083

How can I run a callback after Bootstrap initializes a plugin from data attributes?

I have a Bootstrap 4 radio button group. I want to make a state selection based on stored data at page load. If I do that in my script it runs before Bootstrap's initialization of the toggle plugin. Then Bootstrap initializes its state and makes the first button active. This results in multiple buttons having the appearance of being selected.

$('#up').trigger('click');
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
  <label class="btn btn-outline-secondary w-50 active" id="down">
    <input type="radio" name="direction" value="down" checked>Above
  </label>

  <label class="btn btn-outline-secondary w-50" id="up">
    <input type="radio" name="direction" value="up">Below
  </label>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

However, if I delay a while the selection happens cleanly.

setTimeout(function() {
  $('#up').trigger('click');
}, 200);
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
  <label class="btn btn-outline-secondary w-50 active" id="down">
    <input type="radio" name="direction" value="down" checked>Above
  </label>

  <label class="btn btn-outline-secondary w-50" id="up">
    <input type="radio" name="direction" value="up">Below
  </label>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

It's not a matter of using a zero-delay timeout to skip a cycle. That isn't reliable. I have to use an arbitrarily long timeout to wait for Bootstrap. I'd much rather use a callback for better timing.

I realize that I could remove the checked attribute from the first button, but then I'd need to set a default in code. I'd rather find a way to run a callback on Bootstrap.

I haven't been able to find anything regarding events for plugins initialized only with data attributes, nor have I found an all done event for Bootstrap as a whole. What are my options here?

Upvotes: -1

Views: 178

Answers (1)

Abdelrahman Mahmoud
Abdelrahman Mahmoud

Reputation: 124

you can remove checked attribute from first radio input in your code and make it depend on your state

When you trigger label (btn) --> bootstrap put active class on this label and make input checked

Upvotes: 1

Related Questions