So I have a menu, where models pop-up on click. In each model, there's a close button, marked by an "x". Only problem is, that the model does not close, when the "x" is clicked.
I have tried multiple ways of filing this seemingly simple problem. But with no luck.
I have tried, using a z-index property, I have tried fiddling with the divs. I have tried to link to bootstrap external links. I have tried different kind of "close" button. I have tried to modifying the javascript code. Still I have not arrived at the desired outcome. Can anyone help ?
Here's my code
window.onload = function () {
list = document.querySelectorAll(".Project");
for (let i = 0; i < list.length; i++) {
list[i].addEventListener("click", function (e) {
e.preventDefault();
let currentElement = e.target.parentNode;
let modalId = currentElement.dataset.modal;
let modal = document.getElementById(modalId);
modal.style.display = "block";
});
}
};
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<li class="Project" data-modal="myModal_1">
<span id="myBtn_1"> Wer Baut Der Stadt </span>
<span id="year"> 2019 </span>
<div class="Describtion">
<p style="display:none;">
Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.
</p>
</div>
<div id="myModal_1" class="modal">
<div class="modal-content">
<img src="Images/WER BAUT 2018/HVIDAktiv 20.png" width="1000px">
<span class="close">× </span>
<p> Some text in the Modal..1 </p>
</div>
</div>
</li>
It is very easy to use modal in Bootstrap.
You just have to make sure that, as in the example below, jquery.js, popper.js and bootstrap.js are placed in order.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
this is because you have a bad use of JS event delegation.
the corect way is tu use the matches method https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
like this :
window.onload = function () {
list = document.querySelectorAll(".Project");
document.querySelectorAll(".Project").forEach(LIelm=>{
LIelm.addEventListener('click', showHideModal)
})
};
function showHideModal(e) {
if (!e.target.parentNode.matches('.Project , .modal-content' )) return
e.preventDefault();
let currentParent = e.target.parentNode;
if (currentParent.matches('.Project') ){
document.getElementById( currentParent.dataset.modal ).style.display = "block";
}
else {
currentParent.parentNode.style.display = "";
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<li class="Project" data-modal="myModal_1">
<span id="myBtn_1"> Wer Baut Der Stadt ee</span>
<span id="year"> 2019 </span>
<div class="Describtion">
<p style="display:none;">
Identity and Font developed for the lecture series on architecture conducted by No Image in Berlin.
</p>
</div>
<div id="myModal_1" class="modal">
<div class="modal-content">
<img src="https://picsum.photos/200/300" >
<span class="close">× </span>
<p>Some text in the Modal..1
</p>
</div>
</div>
</li>
Related
I am creating a simple bug tracker that uses a modal to pop up different bugs. The problem I have is that when I delete a bug, there is a thin grey box where the background of the modal was. So basically the list of bugs is empty but it shows the background of the modal even when it should not be there. For example , if you load up the files and open with live server; create a new bug, then delete the bug, you will see the grey box where the bug was just at. I am trying to have the background not be there, when there is no bugs in the list. Any help is greatly appreciated.
I have tried changing the opacity of the modal and issuesList as well as background color, but tbh I am completely lost on how to dynamically change the opacity.
Index.html
<!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">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous">
<script src="https://kit.fontawesome.com/4582c8b826.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/css/styles.css">
<title>Issue Tracker</title>
</head>
<body>
<div class="contaienr">
<h1>Issue Tracker</h1>
<div class="jumbotron">
<h3>Add New Issue:</h3>
<form id="issueinputform">
<div class="form-group">
<label for="issueDescription">Description</label>
<input type="text" class="form-control" id="issueDescription" placeholder="Describe the issue ...">
</div>
<div class="form-group">
<label for="issueSeverity">Severity</label>
<select class="form-control" id="issueSeverity">
<option value="Low">Low</option>
<option value="Medium">Medium</option>
<option value="High">High</option>
</select>
</div>
<div class="form-group">
<label for="issueAssignedTo">Assigned To</label>
<input type="text" class="form-control" id="issueAssignedTo" placeholder="Enter responsible ...">
</div>
<button id="add-issue" onclick="submitIssue()" class="btn btn-primary">Add</button>
</form>
</div>
<div class="col-lg-12">
<div id="issuesList">
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="emptyField" tabindex="-1" role="dialog" aria-labelledby="emptyFieldLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="emptyFieldLabel">Invalid Input!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Please provide the desciption of the issue and also the person name who you want to assign the issue.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.min.js" integrity="sha384-mQ93GR66B00ZXjt0YO5KlohRA5SY2XofN4zfuZxLkoj1gXtW8ANNCe9d5Y3eG5eD" crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>
app.js
function submitIssue(e) {
const getInputValue = id => document.getElementById(id).value;
const description = getInputValue('issueDescription');
const severity = getInputValue('issueSeverity');
const assignedTo = getInputValue('issueAssignedTo');
const id = Math.floor(Math.random() * 100000000) + '';
const status = 'Open';
if ((description.length == 0) || (assignedTo.length == 0)) {
alert("Please fill all fields with required data.");
document.getElementById('add-issue').setAttribute("data-toggle", "modal");
document.getElementById('add-issue').setAttribute("data-target", "#emptyField")
}
else {
document.getElementById('add-issue').removeAttribute("data-toggle", "modal");
document.getElementById('add-issue').removeAttribute("data-target", "#emptyField")
const issue = { id, description, severity, assignedTo, status };
let issues = [];
if (localStorage.getItem('issues')) {
issues = JSON.parse(localStorage.getItem('issues'));
}
issues.push(issue);
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
}
const closeIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const currentIssue = issues.find(issue => issue.id == id);
currentIssue.status = 'Closed';
currentIssue.description = `<strike>${currentIssue.description}</strike>`
localStorage.setItem('issues', JSON.stringify(issues));
fetchIssues();
}
const deleteIssue = id => {
const issues = JSON.parse(localStorage.getItem('issues'));
const remainingIssues = issues.filter(issue => ((issue.id) != id))
localStorage.removeItem('issues');
localStorage.setItem('issues', JSON.stringify(remainingIssues));
fetchIssues();
}
const fetchIssues = () => {
const issues = JSON.parse(localStorage.getItem('issues'));
const issuesList = document.getElementById('issuesList');
issuesList.innerHTML = '';
for (let i = 0; i < issues.length; i++) {
const { id, description, severity, assignedTo, status } = issues[i];
issuesList.innerHTML += `<div class="well">
<h6>Issue ID: ${id} </h6>
<p><span class="label label-info"> ${status} </span></p>
<h3> ${description} </h3>
<p><i class="fa-solid fa-bolt"></i> ${severity}</p>
<p><i class="fa-solid fa-user"></i> ${assignedTo}</p>
<button onclick="closeIssue(${id})" class="btn btn-warning">Close</button>
<button onclick="deleteIssue(${id})" class="btn btn-danger">Delete</button>
</div>`;
}
}
fetchIssues();
styles.css
*{
box-sizing: border-box;
}
.jumbotron{
background: rgb(225, 224, 224);
margin-top: 20px;
margin-left: 150px;
margin-right: 150px;
padding-left: 60px;
padding-right: 60px;
padding-top: 50px;
padding-bottom: 50px;
border-radius: 6px;
}
.container{
}
p{
margin: 0 0 10px;
}
h1{
font-size: 36px;
margin-top: 20px;
margin-bottom: 10px;
margin-left: 150px;
}
/* .col-lg-12{
display: block;
font-size: 14px;
line-height: 1.42857143;
color: #333;
} */
#issuesList{
padding-top: 40px;
padding-left: 20px;
padding-right: 20px;
padding-bottom: 20px;
display: block;
margin-left: 170px;
margin-right: 170px;
margin-top: 40px;
margin-bottom: 20px;
background-color: rgb(233, 233, 233);
border-radius: 6px;
border: solid grey transparent ;
border-width: thin;
}
h6{
font-size: 12px;
font-family: inherit;
margin-bottom: 10px;
}
h3{
margin-bottom: 10px;
margin-top: 30px;
font-weight: 500;
line-height: 1.1;
}
.label{
background-color: #5bc0de;
border: solid rgb(10, 198, 240);
border-radius: 0.25em;
padding: 3px;
color: white;
line-height: 1;
font-weight: 700;
font-size: 75%;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
}
#add-issue{
margin-top: 20px;
}
.container::after{
clear: both
}
.modal
{
opacity:0.5 !important;
}
I'cant get this straight, been on this for quite some time. Basically, I'm on this movie app and need a modal. So far I got to point to show each movie individually, show their poster, title and score.
Now, the idea is to press on title and modal will pop up with description ${overview}. Okay, it works, BUT! Modal only shows first object's description, no matter on which movie's title I press.
Once you remove a modal and add a <div>${overview}</div> it works, shows description of each movie correctly, but once I put it in modal - won't work.
I tried to play around with on click with that button, googled all around but can't find a solution. Any help or direction would be amazing, thank you!
Please see code here: https://github.com/sscip/movie-app-ms2
You need change data-bs-target to bind different button and modal.
movies.forEach((movie) => {
const {poster_path, title, vote_average, overview, uid} = movie; // Pulling necessary names from API
console.log(overview)
const movieBox = document.createElement("div"); //creating a div for individual movie elements
movieBox.classList.add("movie"); // creating a class for it
movieBox.innerHTML = `
<div class="movie-image"><img src="${IMGPath + poster_path}" alt="${title}" /></div>
<div class="movie-info">
<button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#${uid}">
${title}
</button>
<span class="${classByRating(vote_average)}">${vote_average}</span>
<div class="modal fade" id="${uid}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
${overview}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
`; // creating markup for every movie element and pulling information from API
mainSection.appendChild(movieBox); // sending back to HTML file
});
varying-modal-content
Yeah you were basically missing two things:
Text color for the modal content
Unique id for each button and modal
Here is a working solution:
P.S: You can also check it at on JSfiddle here.
// API link with key, please follow readme how to create own API key for application to work.
const APIKey = 'dontreallyneedit';
const APIURL = "https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=" + APIKey + "&page-1";
const IMGPath = "https://image.tmdb.org/t/p/w1280";
const SearchAPI = "https://api.themoviedb.org/3/search/movie?&api_key=" + APIKey + "&query=";
const mainSection = document.getElementById("main-section"); // selecting DOM element to work with
const searchForm = document.getElementById("search-form");
const searchInput = document.getElementById("search-field");
movies(APIURL); // calling popular movies funcion to work
async function movies(url) {
/* const resp = await fetch(url);
const respData = await resp.json(); */
const results = [{
poster_path: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP4mb3V7kJHqWTf5GUr-wHUOfHaTv71Ypf3-WGYqjJr-OpYPJslwk2IYY-Phi4hGxpfFQ&usqp=CAU",
title: "Movie 1",
vote_average: 5,
overview: "Great Overview One!"
},
{
poster_path: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP4mb3V7kJHqWTf5GUr-wHUOfHaTv71Ypf3-WGYqjJr-OpYPJslwk2IYY-Phi4hGxpfFQ&usqp=CAU",
title: "Movie 2",
vote_average: 4,
overview: "Great Overview Two!"
},
{
poster_path: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTP4mb3V7kJHqWTf5GUr-wHUOfHaTv71Ypf3-WGYqjJr-OpYPJslwk2IYY-Phi4hGxpfFQ&usqp=CAU",
title: "Movie 3",
vote_average: 3,
overview: "Great Overview Three!"
}
];
showMovies(results);
}
function showMovies(movies) {
mainSection.innerHTML = ""; // clearing page to show new reults
movies.forEach((movie, index) => {
const {
poster_path,
title,
vote_average,
overview
} = movie; // Pulling necessary names from API
const movieBox = document.createElement("div"); //creating a div for individual movie elements
movieBox.classList.add("movie"); // creating a class for it
movieBox.innerHTML = `
<div class="movie-image"><img src="${poster_path}" alt="${title}" /></div>
<div class="movie-info">
<button type="button" class="btn" data-bs-toggle="modal" data-bs-target="#exampleModal_${index}">
${title}
</button>
<span class="${classByRating(vote_average)}">${vote_average}</span>
<div class="modal fade" id="exampleModal_${index}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">${title}</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
${overview}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
`; // creating markup for every movie element and pulling information from API
mainSection.appendChild(movieBox); // sending back to HTML file
});
}
function classByRating(vote) { //checking how high is the movie rating and giving apropriate class name.
if (vote >= 8) {
return "green";
} else if (vote >= 5) {
return "amber"
} else {
return "red";
}
}
searchForm.addEventListener("submit", (i) => {
i.preventDefault();
const searchTerm = searchInput.value;
if (searchTerm) {
movies(SearchAPI + searchTerm)
searchInput.value = "";
}
})
#import url('https://fonts.googleapis.com/css2?family=Lato:wght#100;300&display=swap');
.modal-content {
color: black;
}
/* Main Styles */
* {
box-sizing: border-box;
font-family: 'Lato', serif;
}
/* Navigation */
header {
background-color: #D16BA5;
padding: 1rem 0.5rem;
}
header a {
font-size: 1.5rem;
}
header button:focus {
outline: none;
}
#navbar-brand {
font-size: 1.7rem;
}
#search-field {
border-radius: 10px;
font-size: 1.2rem;
border: none;
}
.search-btn:focus {
outline: none;
}
.search-btn:active {
background-color: #FF8F80;
}
.search-btn {
font-size: 1.2rem;
padding: 0 1rem;
border: none;
border-radius: 10px;
color: #eee;
background-color: #FF8F80;
}
/* Main section styling */
#main-section {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
/* Movies Box styling */
.movie {
margin: 0.7rem;
width: 15rem;
border-radius: 5px;
background-color: #FF8F80;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
/* Movie image */
.movie img {
max-width: 100%;
}
/* Movie Basic info */
.movie-info {
display: flex;
justify-content: space-between;
color: #eee;
padding: 0.5rem;
align-items: center;
max-height: 100%;
}
.movie-info h3 {
margin: 0;
font-size: 1.21rem;
}
.movie-info span {
background-color: #D16BA5;
padding: 0.5rem;
border-radius: 5px;
width: 2.5rem;
height: 2.5rem;
text-align: center;
font-weight: bold;
}
.movie-info span.green {
color: rgb(0, 214, 54);
}
.movie-info span.amber {
color: rgb(255, 163, 87);
}
.movie-info span.red {
color: rgb(223, 45, 0);
}
<!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 -->
<title>Movies TOP-20 LIVE!</title>
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<!-- Font Awesome 5 -->
<script src="https://kit.fontawesome.com/0d4c39c5bf.js" crossorigin="anonymous"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="assets/css/styles.css" />
<!-- Custom JS -->
<script src="assets/js/config.js" type="text/javascript" defer></script>
<script src="assets/js/script.js" type="text/javascript" defer></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" id="navbar-brand" href="#">Movies TOP-20 LIVE</a>
<button class="navbar-toggler" id="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact Us</a>
</li>
</ul>
<form class="d-flex" id="search-form">
<input class="form-control me-2" id="search-field" type="search" placeholder="Search" aria-label="Search">
<button class="search-btn" id="search-btn" type="submit">
Search
</button>
</form>
</div>
</div>
</nav>
</header>
<section id="main-section"></section>
<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>
</html>
I was an issue with creating cookies to do not ask checkboxI want to create this type popup also cookies in website here is my html and js code please reviews my code and please help me sort this problem.
enter image description here
enter image description here
$("div[id^='myModal']").each(function(){
var currentModal = $(this);
//click next
currentModal.find('.btn-next').click(function(){
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").nextAll("div[id^='myModal']").first().modal('show');
});
//click prev
currentModal.find('.btn-prev').click(function(){
currentModal.modal('hide');
currentModal.closest("div[id^='myModal']").prevAll("div[id^='myModal']").first().modal('show');
});
});
//do not show function
jQuery(document).ready(function($) {
/*if ($.cookie("cacher-modal")) {
$("#popupMaintenanceModal").remove();
} else {
$("#popupMaintenanceModal").modal("show");
}*/
$("#popupMaintenanceCheckbox").click(function() {
if ($(this).is(":checked")) {
$("#myModal1").hide();
$(".modal-backdrop").hide();
console.log("here");
$.cookie("cacher-modal", true);
} else {
$.cookie("cacher-modal", false);
}
});
//checkbox for popup-cookies
$('#showNextpop').click(function(){
if ($.cookie("cacher-modal")) {
//$("#popupMaintenanceModal").remove();
} else {
$("#myModal1").modal("show");
}
});
});
$('#showNextpop1').click(function(){
if ($.cookie("cacher-modal")) {
//$("#popupMaintenanceModal").remove();
} else {
$("#myModal1").modal("show");
}
});
$('#showNextpop2').click(function(){
if ($.cookie("cacher-modal")) {
//$("#popupMaintenanceModal").remove();
} else {
$("#myModal1").modal("show");
}
});
$('#showNextpop3').click(function(){
if ($.cookie("cacher-modal")) {
//$("#popupMaintenanceModal").remove();
} else {
$("#myModal1").modal("show");
}
});
jQuery(document).ready(function($) {
if ($.cookie("cacher-modal")) {
$("#popupMaintenanceModal1").remove();
} else {
$("#popupMaintenanceModal1").modal("show");
}
$("#popupMaintenanceCheckbox1").click(function() {
if ($(this).is(":checked")) {
$("#myModal2").hide();
$(".modal-backdrop").hide();
console.log("here");
$.cookie("cacher-modal", true);
} else {
$.cookie("cacher-modal", false);
}
})
});
jQuery(document).ready(function($) {
if ($.cookie("cacher-modal")) {
$("#popupMaintenanceModal2").remove();
} else {
$("#popupMaintenanceModal2").modal("show");
}
$("#popupMaintenanceCheckbox2").click(function() {
if ($(this).is(":checked")) {
$("#myModal3").hide();
$(".modal-backdrop").hide();
console.log("here");
$.cookie("cacher-modal", true);
} else {
$.cookie("cacher-modal", false);
}
})
});
jQuery(document).ready(function($) {
if ($.cookie("cacher-modal")) {
$("#popupMaintenanceModal3").remove();
} else {
$("#popupMaintenanceModal3").modal("show");
}
$("#popupMaintenanceCheckbox3").click(function() {
if ($(this).is(":checked")) {
$("#myModal4").hide();
$(".modal-backdrop").hide();
console.log("here");
$.cookie("cacher-modal", true);
} else {
$.cookie("cacher-modal", false);
}
})
});
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true" style="top:120px;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Modal title 1</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<div class="d-flex justify-content-start custom-control custom-checkbox1">
<input id="popupMaintenanceCheckbox" for="popupMaintenanceCheckbox" type="checkbox" name="coupon_question" />
<span class="item-text">Don't show me again</span>
</div>
<button type="button" class="btn btn-default btn-next">Next</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true" style="top:120px;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Modal title 2</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<div class="d-flex justify-content-start custom-control custom-checkbox2">
<input id="popupMaintenanceCheckbox1" for="popupMaintenanceCheckbox1" type="checkbox" name="coupon_question" />
<span class="item-text">Don't show me again</span>
</div>
<button type="button" class="btn btn-default btn-prev">Prev</button>
<button type="button" class="btn btn-default btn-next">Next</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="myModal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true" style="top:120px;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Modal title 3</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<div class="d-flex justify-content-start custom-control custom-checkbox2">
<input id="popupMaintenanceCheckbox2" for="popupMaintenanceCheckbox2" type="checkbox" name="coupon_question" />
<span class="item-text">Don't show me again</span>
</div>
<button type="button" class="btn btn-default btn-prev">Prev</button>
<button type="button" class="btn btn-default btn-next">Next</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Button trigger modal -->
<!-- Modal -->
<div class="modal fade" id="myModal4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true" style="top:120px;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Modal title 4</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<div class="d-flex justify-content-start custom-control custom-checkbox1">
<input id="popupMaintenanceCheckbox3" for="popupMaintenanceCheckbox3" type="checkbox" name="coupon_question" />
<span class="item-text">Don't show me again</span>
</div>
<button type="button" class="btn btn-default btn-prev">Prev</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
So we are going to create a popup with a message and buttons, and a checkbox which saves a setting in a cookie to prevent the popup in the future. Here it is. You won't be able to test it here because the cookies are blocked.
**** UPDATE
Open in external sandbox to see how the cookie works
// You need to save the message data somewhere so you can change it without touching the code. We are going to save it in an object but ideally should be in a database or external JSON file.
const popup_msg_data = {
headline: "How to play",
message: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce turpis est, eleifend non felis id, blandit sodales quam. Nam tortor lorem, porta at enim id, aliquam eleifend lorem.",
checkbox_text: "Don't show this again."
}
// Create variable with our cookie name
const cname = "message_popup_suppress_option_enabled";
// Handler for the checkbox
$("body").on("change", "#popup_suppress", function() {
console.log("input changed");
// Check if checkbox is checked.
const checked = $(this).is(":checked");
if (checked && !cookie_exists()) {
// Set the cookie if not already there
set_suppress_cookie();
} else if (!checked) {
// Delete the cookie if already exists
document.cookie = cname + "; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
});
// Check for the cookie
function cookie_exists() {
// Get cookies into an array
const dcookie = decodeURIComponent(document.cookie).split(';');
// Check for our cookie
return dcookie.includes(cname);
}
// Function to set cookie
function set_suppress_cookie() {
// Create a date object one day into the future to expire our cookie
const expires = new Date();
const exp_days = 1;
expires.setTime(expires.getTime() + (exp_days * 24 * 60 * 60 * 1000));
// Create the cookie
document.cookie = cname + ";expires=" + expires + ";path=/";
}
// This function toggles the popup
$("body").on("click", ".toggle-popup", function() {
// Check for the template
const template = $(".popup-template");
// initialize a variable for the popup
let popup = $(".popup-container");
// Function to handle closing the popup
function close_popup() {
// Fade out the popup
popup.fadeOut("fast", function() {
// When done fading put the template back and remove the popup
template.appendTo("body");
$(this).remove();
})
}
// If we have a template continue
if (template.length) {
// If popup is visible
if (popup.is(":visible")) {
close_popup();
} else {
// If our cookie is not present continue with the popup
if (!cookie_exists()) {
// If not visible create the basic HTML structure of the popup and insert the template
popup = $("<div />", {
class: "popup-container"
}).append(
$("<div />", {
class: "popup-scroll"
}).append(
$("<div />", {
class: "popup-overlay toggle-popup"
}),
$("<div />", {
class: "popup-content"
}).append(template)
)
);
// Find all elements in template with data-id attribute and loop over them
popup.find("[data-id]").each(function() {
// Get the id
const id = $(this).data("id");
// Match the id from the element with the right key from our data object and insert text.
$(this).text(popup_msg_data[id] || null);
})
// Append the popup to the dom and add active class
popup.appendTo("body").hide(1, function() {
$(this).fadeIn("fast", function() {
$(this).removeClass("active").addClass("active");
})
});
} else {
console.log("Cookie detected");
}
} // End if visible
} // End if template
})
* {
box-sizing: border-box;
}
body,
html {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
background: slategray;
font-size: 16px;
line-height: 1.4em;
font-family: sans-serif;
}
button.test-btn {
appearance: none;
-webkit-appearance: none;
border: none;
outline: none;
background: cyan;
padding: 12px;
color: black;
}
.popup-template {
display: none;
}
.popup-container {
display: flex;
position: fixed;
z-index: 95000;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.popup-scroll {
display: flex;
position: absolute;
top: 0;
left: 0;
padding: 30px 15px;
width: 100%;
height: 100%;
overflow-y: scroll;
-webkit-overflow-scrolling: touch;
z-index: 1;
}
.popup-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: black;
opacity: .8;
cursor: pointer;
z-index: 1;
}
.popup-content {
position: relative;
z-index: 10;
margin: auto;
opacity: 0;
transform: translate(0, 100px);
transition: opacity .4s, transform .4s ease-out;
}
.popup-container.active .popup-content {
opacity: 1;
transform: none;
}
.popup-content .popup-template {
display: grid;
grid-gap: 20px;
background: black;
color: GhostWhite;
padding: 30px;
position: relative;
max-width: 800px;
}
.popup-hdr {
display: grid;
grid-template-columns: 1fr max-content;
grid-gap: 20px;
align-items: center;
width: 100%;
}
.popup-hdr h2 {
font-size: 1.4em;
line-height: 1.3em;
margin: 0;
color: white;
}
.popup-info {
font-size: .8em;
line-height: 1em;
text-align: right;
}
.popup-ftr {
display: grid;
grid-gap: 20px;
grid-template-columns: 1fr max-content;
}
.popup-check {
display: flex;
align-items: center;
position: relative;
}
.popup-check input {
display: none;
}
.popup-check label {
cursor: pointer;
display: grid;
grid-auto-flow: column;
justify-content: flex-start;
grid-gap: 10px;
align-items: center;
}
.popup-check label:before {
content: "";
display: flex;
justify-content: center;
align-items: center;
text-align: center;
width: 22px;
height: 22px;
background: transparent;
border: 2px solid white;
overflow: hidden;
font-family: "Font Awesome 5 Free", sans-serif;
font-weight: 600;
color: SpringGreen;
font-size: 14px;
line-height: 1;
}
.popup-check input:checked+label:before {
content: "\f00c";
}
.popup-btns {
display: grid;
grid-auto-flow: column;
grid-gap: 10px;
}
.popup-btn {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
padding: 12px;
min-width: 90px;
min-height: 48px;
border: 1px solid white;
cursor: pointer;
}
.popup-btn:hover {
background: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" crossorigin="anonymous" />
<!-- This is the button that will trigger the popup. You may need to change this for your use case -->
<button class="test-btn toggle-popup">Click Here</button>
<!-- This is the template for the popup. Ideally this should be in an external file -->
<div class="popup popup-template">
<div class="popup-hdr">
<h2 data-id="headline"></h2>
<div class="popup-info">5 of 6</div>
</div>
<div data-id="message" class="popup-text"></div>
<div class="popup-ftr">
<div class="popup-check">
<input type="checkbox" id="popup_suppress" />
<label for="popup_suppress" data-id="checkbox_text">
Do not show again
</label>
</div>
<div class="popup-btns">
<div class="popup-btn toggle-popup">Close</div>
<div class="popup-btn" data-action="back">Back</div>
<div class="popup-btn" data-action="next">Next</div>
</div>
</div>
</div>
I am doing a project where I have a table with several rows and in one of the columns of the table I have buttons that when clicked show a modal.
This modal has a input and a div where the input written will appear.
The problem is what I write in a single modal appears in the other modals.
Is there a way to make them "independent"? Below is the code I have written.
When you run the snippet below, that's something like that that appears in the
modal. And the text that you write in the input and goes to the div, is what is repeating in all the modals.
$(document).ready(function() {
// send message to modal if message is empty do not send anything or if it is only spaces
$("#sendMessage").click(function() {
if ($.trim($("#inputToSend").val()) == "") {
//do not send anything
} else {
$(".textModal").append(
'<p class="msg">' + $("#inputToSend").val() + "</p>"
);
$("#inputToSend")
.val("")
.focus();
}
});
// when modal button is closed text is erased
$(".modal").on("hidden.bs.modal", function() {
$(".modal-body").html("");
$(".modal-title").html("");
});
});
.modal-title {
background: #66a3ff;
font-size: 18px;
display: inline-block;
height: 100%;
}
.modal-body {
padding: 30px 20px;
font-size: 16px;
text-transform: uppercase;
text-align: center;
}
#messageInput {
padding: 0px 20px;
}
#sendMessage {
margin: 15px 0px;
}
#inputToSend {
margin-top: 25px;
margin-left: 15px;
width: 730px;
}
#messageSaved {
margin: 0px 15px;
font-size: 16px;
padding: 10px;
border: inset;
height: 100px;
overflow: auto;
text-align:justify;
}
.msg {
margin: 0 0 10px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="fa fa-envelope-o"></i>
<div class="modal fade" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h6 class="modal-title" id="title"></h6>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div id="messageInput">
<div id="messageSaved" class="textModal"></div>
<input id="inputToSend" type="text" class="text form-control" placeholder="Insert Message...">
<button id="sendMessage" class="btn btn-primary">Enviar</button>
</div>
</div>
</div>
</div>
That happens because you are referring to the .modal-body with $(".modal-body"), and there are probably more modals with the same class name
You should be more specific if you want to refer to a specific modal.
You can replace $(".modal-body") with $("#basicModal .modal-body") to select only the .modal-body that is under the parent #basicModal
I created a popup with bootstrap to store several Social media share buttons. Then I created two left and right buttons to navigate between them. My logic is, if modal-body width is less than share buttons content div width, then navigation buttons should be appeared and move to the very end in both sides. Here, in my code, I'm getting wrong modal-body width and therefore right-side navigation button is not working as expected which is I can't go to the last share button. It seems perfectly working with the default loading screen size. The Problem can be exactly seen by reducing the screen size and trying to navigate to the last share button. What I missed here?
$('.modal').on('show.bs.modal', function () {
var currentPos = 0;
var shareBtns = $(".a2a_kit a").length;
var sampleDivWidth = $(".a2a_button_facebook span").width();
var actualButtonWidth = sampleDivWidth + 26
var shareDivWidth = (actualButtonWidth * shareBtns) / 3;
var mainDivWidth = $(".modal-body").width();
//var mainDivWidth = 445;
var x = shareDivWidth / actualButtonWidth;
var y = mainDivWidth / actualButtonWidth;
var z = (x - y);
var stopPos = z * (-actualButtonWidth);
//alert(mainDivWidth);
if( (mainDivWidth - 30) < shareDivWidth ) {
$(".move-btn").css("display", "block");
}
else {
$(".move-btn").css("display", "none");
}
if ( currentPos === 0 ) {
$(".move-btn-l").css("display", "none");
}
$(".move-btn-r").on("click", function() {
$(".a2a_kit").animate({
left : ""+ (currentPos -= 66) +"px"
}, 200);
$(".move-btn-l").css("display", "block");
if (currentPos <= stopPos) {
$(".move-btn-r").css("display", "none");
}
})
$(".move-btn-l").on("click", function() {
$(".a2a_kit").animate({
left : ""+ (currentPos += 66) +"px"
}, 200);
$(".move-btn-r").css("display", "block");
if (currentPos == 0) {
$(".move-btn-l").css("display", "none");
}
})
})
.share-link-div{
overflow: hidden;
width: 75%;
margin: auto;
}
.a2a_kit {
display: inline-flex;
position: relative;
width: max-content;
}
.a2a_kit a .a2a_svg {
border-radius: 50% !important;
padding: 5px;
width: 50px;
height: 50px;
float: none !important;
}
.a2a_kit a:hover {
text-decoration: none !important;
}
.move-btn{
background-color: #fff;
border: 1px solid #ccc;
border-radius: 50%;
width: 35px;
height: 35px;
position: absolute;
top: 20px;
cursor: pointer;
box-shadow: 0 3px 3px #7d7d7d;
}
.move-btn-r {
right: 15px;
}
.move-btn-l {
left: 15px;
}
.move-btn span{
margin-left: 12px;
margin-top: 6px;
position: absolute;
}
.embed-btn .a2a_svg {
float: left;
background-color: #dedede;
color: #000;
font-size: 12px;
height: 32px;
font-weight: 600;
}
.embed-btn .a2a_svg:hover {
opacity: 0.7;
}
.embed-btn .a2a_svg p {
margin: 0px;
top: 5px;
position: relative;
text-align: center;
}
.embed-src{
padding: 10px;
border: 1px solid #ececec;
background-color: #fafafa;
font-size: 14px;
font-weight: 400;
}
.embed-button{
overflow: hidden;
display: flex;
margin-top: 20px;
}
.embed-button .embed-src {
float: left;
width: 100%;
}
.copy-iframe {
border-radius : 0 4px 4px 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script async src="https://static.addtoany.com/menu/page.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="share-link-div">
<div class="a2a_kit a2a_kit_size_32 a2a_default_style">
<a class="a2a_button_facebook"></a>
<a class="a2a_button_twitter"></a>
<a class="a2a_button_google_plus"></a>
<a class="a2a_button_pinterest"></a>
<a class="a2a_button_facebook"></a>
<a class="a2a_button_twitter"></a>
<a class="a2a_button_google_plus"></a>
<a class="a2a_button_pinterest"></a>
<a class="a2a_button_facebook"></a>
<a class="a2a_button_twitter"></a>
<a class="a2a_button_google_plus"></a>
<a class="a2a_button_pinterest"></a>
</div>
<div class="move-btn move-btn-l">
<span><</span>
<!-- <i class="fas fa-chevron-left"></i> -->
</div>
<div class="move-btn move-btn-r">
<span>></span>
<!-- <i class="fas fa-chevron-right"></i> -->
</div>
</div>
<div class="embed-button">
<div class="embed-src">
<span>URL and Code</span>
</div>
<button type="button" class="btn btn-primary copy-iframe">Copy</button>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Here is the editable code :
http://jsfiddle.net/rgL2ak0z/3/
I think you cant get width of dynamicaly created div without prior width initialization. Maybe you could get width of document and calculate it? Like:
var mainDivWidth=document.documentElement.clientWidth;