Search code examples
javascriptjqueryhtmltwitter-bootstrapbootstrap-modal

Create Bootstrap Modal from JavaScript


I am trying to include a JS CDN script to show a message on specific actions. To achieve that I am trying to make it work firstly on any browser.

This is what I am trying to do:

document.querySelector('.circle').addEventListener('click', function() {
  var m1 = $(makeModal('Somehting here')); // I would want to skip creating an HTML element with jQuery.
  document.body.insertAdjacentHTML('beforeend', m1);
  m1.modal('show');
}, false);

function makeModal(text) {
  return `<div id="myModal" class="modal fade" role="dialog" style="display: none">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>${text}</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>`;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>An app</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <button class="circle">Click here</button>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  
</body>
</html>

This works, but the phrase [object Object] is appended to the button. Another thing, I guess everytime someone clicks on the button the node is created again and again.

Should I delete it after the modal appears? Well, how would you ahieve this stuff?


Solution

  • this code cause the [object Object] :

    document.body.insertAdjacentHTML('beforeend', m1);
    

    And when i tried without this code, all works perfectly, why did you use it ?

    If he is not usefull, you can just delete him.