Search code examples
javascripthtmlcssweb-frontend

Bootstrap3 Toggle appearing only once as Toggle


I didn't find any question that could help me. I'm not using Bootstrap4, so, if there's any other solution besides changing Bootstrap version, it would be appreciated.

I'm web developing with Node.js, CSS, HTML and Javascript. My website has two checkboxes that I'm changing to Toggles. On my code, the Toggles are set as such:

'<div class="options">'
        '<input type="checkbox" id="draw-line" checked data-toggle="toggle" data-size="mini" data-on="Traçar trajetória" data-off="Traçar trajetória"/>'
        '</div>'
        '<div class="options mrg-botm" style="margin-top: 5px">'
        '<input type="checkbox" id="show-info" checked data-toggle="toggle" data-size="mini" data-on="Informações de localização" data-off="Informações de localização"/>'
        '</div>'

This code is appended to the HTML body when an History button is clicked and is removed when a Close button is clicked. We also have a handy tool created to make these Toggles reactive. (There are variables directly listening to the Toggle button, long story short).

Toggles working

But, when I open the same panel with the Toggles, they show up like that:

Toggles vanished

The whole code that's added to the HTML document when the History button is clicked is below (key parts with comments):

new ScopedWatcher(
  () => watch.historyPanel.value,
  async () => {
    if (watch.historyPanel.value) {
    // here, the panel DIV code
      var historyPanelCode =
        '<div id="hist-loc-control-panel" class="draggable floating-panel">' +
        '<span class="title"><b>Histórico de localização</b></span><br>' +
        '<div class="input-group date" id="datetimepicker_from" style="width: 200px;">' +
        '<input type="text" class="form-control" id="date_from" />' +
        '<span class="input-group-addon">' +
        '<span class="fa fa-calendar"></span>' +
        '</span>' +
        '</div>' +
        'até' +
        '<div class="input-group date" id="datetimepicker_to" style="width: 200px; margin-bottom: 5px">' +
        '<input type="text" class="form-control" id="date_to" />' +
        '<span class="input-group-addon">' +
        '<span class="fa fa-calendar"></span>' +
        '</span>' +
        '</div>' +
        '<div>' +
        'Empréstimo' +
        '</div>' +
        '<div>' +
        '<select id="leasing_option" style="margin-bottom: 5px;">' +
        '<option value="1">Atual</option>' +
        '<option value="2">Todos do dispositivo</option>' +
        '<option value="3">Todos do colaborador atual</option>' +
        '</select>' +
        '</div>' +
        '<button class="btn btn-primary btn-xs search mrg-botm">Buscar</button>' +
        '<div id="history-location-position-info" class="btn-xs"></div>' +
        '<button class="btn btn-success btn-xs hist-loc-button" id="first" disabled><<</button>' +
        '<button class="btn btn-success btn-xs hist-loc-button" id="back" disabled><</button>' +
        '<button class="btn btn-success btn-xs hist-loc-button" id="forward">></button>' +
        '<button class="btn btn-success btn-xs hist-loc-button" id="last">>></button>' +
        '<div class="mrg-botm"></div>' +
        '<div class="options">' +
        '<input type="checkbox" id="draw-line" checked data-toggle="toggle" data-size="mini" data-on="Traçar trajetória" data-off="Traçar trajetória"/>' +
        '</div>' +
        '<div class="options mrg-botm" style="margin-top: 5px">' +
        '<input type="checkbox" id="show-info" checked data-toggle="toggle" data-size="mini" data-on="Informações de localização" data-off="Informações de localização"/>' +
        '</div>' +
        '<div class="options"><label style="vertical-align:middle">Deslocamento total aproximado: </label></br><label style="vertical-align:middle" id="sum-distance"></label></div></br>' +
        '<div><button id="close-history-btn" class="btn btn-warning btn-xs">Fechar histórico</button><br></div>' +
        '</div>'
      $('body').append($(historyPanelCode))
      $('.draggable').draggable()
      $('#datetimepicker_from')
        .datetimepicker({
          defaultDate: new Date().setHours(0, 0, 0, 0),
          locale: 'pt-br',
          showClose: false,
        })
        .on('dp.change', function () {
          // getHistory(imei);
          $(this).data('DateTimePicker').hide()
        })
      $('#datetimepicker_to')
        .datetimepicker({
          defaultDate: new Date().setHours(23, 59, 0, 0),
          locale: 'pt-br',
          showClose: false,
        })
        .on('dp.change', function () {
          // getHistory(imei);
          $(this).data('DateTimePicker').hide()
        })
      $('#hist-loc-control-panel')
        .on('click', 'button.hist-loc-button', function (event) {
          var selectedMarkerArrayPos = watch.selectedMarkerArrayPos
          var pos
          switch (event.target.id) {
            case 'forward':
              pos = ++selectedMarkerArrayPos
              break

            case 'back':
              pos = --selectedMarkerArrayPos
              break

            case 'last':
              pos = markerArray.length - 1
              break

            default:
              pos = 0
              break
          }
          watch.selectedMarkerArrayPos = pos
          displayInfoMessage(markerArray[watch.selectedMarkerArrayPos])
        })
        .on('click', '#draw-line', function (event) {
          if (watch.toggleLineDraw.value !== false) {
            linePath.setMap(map)
          } else {
            linePath.setMap(null)
          }
        })
        .on('click', '#show-info', function (event) {
          if (watch.showInfo === true) {
            displayInfoMessage(markerArray[watch.selectedMarkerArrayPos])
          } else {
            closeAllInfoWindow()
          }
        })
        .on('click', '#close-history-btn', function () {
          finalizeHistory()
          initializeRTP()
        })
        .on('click', '.search', function () {
          getHistory(watch.historyPanel.id)
        })
      // init() loads the JS bootstrap modules referring to Toggle.
      // thought that running init() just once would solve it...
      // start is a var that counts how many times the HistoryPanel button was clicked.
      if (start < 2) {
        new Toggle('#draw-line', watch.toggleLineDraw).init()
        new Toggle('#show-info', watch.showInfo).init()
      }
    } else {
      $('#hist-loc-control-panel').remove()
    }
  }
)

Solution

  • Reactive toggles only instantiate once. Therefore, the solution is: build it only once.

    I'm building the panel with the Toggles with the whole page, but I made it invisible on start. It only turns visible if the user clicks on the button that leads to the panel.