I want to open custom bootstrap modal using data from an object when double clicked on an element. How to do this using vanilla JavaScript.
Also how to add all functionalities in it :
- Ease Transition
- Modal should remove when clicked on cross or outside of body
- always clear the previous data(no caching)
https://jsfiddle.net/awo0hq4c/
NOTE : Modal used is basic bootstrap modal which is given below but instead of button it is a div in my case
<button type="button" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="exampleModalLabel">Modal title</h5>
<button type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div >
...
</div>
<div >
<button type="button" data-dismiss="modal">Close</button>
<button type="button" >Save changes</button>
</div>
</div>
</div>
</div>```
CodePudding user response:
Append this line of code into the last line of showModal() function.
new bootstrap.Modal(modalItem).show();
https://getbootstrap.com/docs/5.0/components/modal/#via-javascript
const div = document.querySelector('.container');
div.addEventListener('dblclick', (event) => {
showModal({
id: '1',
title: 'Title Modal',
value: 'this is modal content',
});
});
const showModal = (data) => {
console.log(data, 'here is');
const modalItem = document.getElementById('exampleModal');
modalItem.innerHTML = '';
modalItem.innerHTML = ` <div >
<div >
<div >
<h5 id="exampleModalLabel">${data.title}</h5>
<button type="button" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div >
${data.value}
</div>
<div >
<button type="button" data-bs-dismiss="modal">Close</button>
<button type="button" >Save changes</button>
</div>
</div>
</div>
`;
new bootstrap.Modal(modalItem).show();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Modal</title>
<!-- CSS only -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<!-- <link rel="stylesheet" href="./modal.css"> -->
</head>
<body>
<!-- Modal -->
<div
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
></div>
<div >Launch modal</div>
<!-- JavaScript Bundle with Popper -->
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p"
crossorigin="anonymous"
></script>
<!-- <script src="./modal.js"></script> -->
</body>
</html>
