How can I get my modal box in Bootstrap to close? - javascript

I have a modal box which I can call okay but I can't close it, regardless of whether you click on the x or anywhere else on the screen. Sorry if I'm not describing it well enough - I'm very new.
I've tried the w3 schools demo and also other s/o examples and I just can't for the life of me figure out what I'm doing wrong. Full code supplied below as requested.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Benny the virtual blob</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="virtualpet.css">
<link href="https://fonts.googleapis.com/css?family=Barriecito|Special+Elite&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/de2b0ad954.js"></script>
</head>
<body>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<i class="fas fa-skull-crossbones"></i><br>
<p>"Oh, no! You killed Benny!"<br>
"He was <span id="dead">x</span> days young"</p>
</div>
</div>
<div class="container">
<h1>Benny the Blob</h1>
<p>Look after Benny, the blob. Play with him, feed him, care for him when he's sick. But if you ignore him for too long, he'll die. How long will you be able to keep him alive?</p>
<button type="button" class="btn reset">Birth Benny</button>
</div>
<div class="action">
<img id="age" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857600/virtual%20pet/item-box.png" alt="window for life span">
<img id="backing" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561670551/virtual%20pet/little-board.png" alt="pin board image">
<div id="bennyNormal" class="start"></div>
<p id="ageStatus" class="start" ><span id="days">0</span> days old</p>
<img id="heart" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png" alt="health points image">
<img id="star" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png" alt="happy points image">
<img id="hungry" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png" alt="hunger points image">
<div id="tasks">
<img id="medicine" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857719/virtual%20pet/medicene.png" alt="medicine">
<img id="food" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857661/virtual%20pet/sandwich.png" alt="food">
<img id="toys" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857776/virtual%20pet/gamesbox.png" alt="toys">
<img id="drink" class="start" src="https://res.cloudinary.com/dytmcam8b/image/upload/v1561857689/virtual%20pet/red-smoothie.png" alt="glass of juice">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="virtualpet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
var resetBtn = document.querySelector(".reset");
var start = document.querySelectorAll(".start");
var ageing = document.getElementById("days");
var heart= document.getElementById("heart");
var star = document.getElementById("star");
var tummy = document.getElementById("hungry");
var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
var content = document.getElementsByClassName("modal-content")
var dead = document.getElementById("dead");
$(document).ready(function () {
var count=0;
var c = count;
var cd = $('#days');
$(resetBtn).click(function(){
$(".start").toggle();
if ($(this).text() == "Birth Benny") {
$(this).text("Restart");
} else {
$(this).text("Birth Benny");
}});
var interv = setInterval(function() {
c++;
cd.html(c);
randomNum();
happyStatus();
hungerStatus();
healthStatus();
}, 60000);
var health = 4;
var happy = 4;
var hungry = 4;
function randomNum(){
//pick a 'health'
var h=Math.random();
//pick a happy
var s=Math.random();
//pick a hungry
var f=Math.random();
if (h <0.5) {
health--;
}
if (s <0.5) {
happy--;
}
if (f <0.5) {
hungry--;
}
};
function healthStatus(){
if (health===4){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725918/virtual%20pet/l1.png");
}if(health===3){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l2.png");
}if (health===2){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l3.png");
}if(health===1){
$(heart).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725919/virtual%20pet/l4.png");
}if (health===0){
deathScreen();
}
};
function happyStatus(){
if (happy===4){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s1.png");
}if(happy===3){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s2.png");
}if (happy===2){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s3.png");
}if(happy===1){
$(star).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725934/virtual%20pet/s4.png");
}if (happy===0){
deathScreen();
}
};
function hungerStatus(){
if (hungry===4){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h1.png");
}if(hungry===3){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h2.png");
}if (hungry===2){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h3.png");
}if(hungry===1){
$(tummy).attr("src", "https://res.cloudinary.com/dytmcam8b/image/upload/v1561725898/virtual%20pet/h4.png");
}if (hungry===0){
deathScreen();
}
};
function deathScreen(){
$(start).hide();
$('#myModal').modal('show');
$(dead).text(c);
clearInterval(interv);
};
$(span).on("click", function(){
$('#myModal').modal('toggle');
});
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$('#myModal').modal('toggle');
}
}
});
body {
margin: 0;
text-align: center;
}
h1 {
font-family: 'Barriecito', cursive;
text-align: center;
}
p {
font-family: 'Special Elite', cursive;
text-align: left;
}
#ageStatus {
top: -850px;
left: 150px;
position: relative;
font-size: 2em;
display: none;
}
.container {
width: 600px;
margin: 0 auto;
text-align: center;
}
.btn{
background-color: pink!important;
font-family: 'Barriecito', cursive;
}
#backing {
width: 800px;
margin: 0 auto;
z-index: -10;
position: relative;
top: 0px;
display: none;
}
#bennyNormal {
width:327px;
height: 444px;
display: none;
background-image:url("https://res.cloudinary.com/dytmcam8b/image/upload/v1561677299/virtual%20pet/Sheet.png");
top: -450px;
left:250px;
position: relative;
transform: scale(0.5);
-webkit-animation: benny 3s steps(10) infinite;
-moz-animation: benny 1.5s steps(10) infinite;
-ms-animation: benny 1.5s steps(10) infinite;
-o-animation: benny 1.5s steps(10) infinite;
animation: benny 1.5s steps(10) infinite;
}
#-webkit-keyframes benny{
from{background-position:0px;}
to{background-position:-3270px;}
}
}
#keyframes normal{
from {background-position:0px;}
to {background-position:-3270px;}
}
#heart {
height: 150px;
width: 150px;
transform: scale(0.5);
top: -970px;
left: 400px;
position: relative;
display: none;
}
#star {
height: 150px;
width: 150px;
top: -970px;
left: 350px;
transform: scale(0.5);
position: relative;
display: none;
}
#hungry {
height: 80px;
width: 80px;
position: relative;
left: 330px;
top: -970px;
display: none;
}
#age {
width: 250px;
position: relative;
top: 180px;
left: 100px;
display: none;
}
#medicine {
width: 100px;
position: relative;
top: -870px;
left: 150px;
display: none;
}
#toys {
width: 100px;
position: relative;
top:-1000px;
left:-50px;
display: none;
}
.action {
position: relative;
height: 400px;
width: 800px;
margin: 0 auto;
}
#food {
width: 100px;
position: relative;
left: 440px;
top: -1000px;
display: none;
}
#drink{
width: 100px;
position: relative;
left: 240px;
top: -900px;
display: none;
}
.hidden {
display: block;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 100; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(242, 114, 223); /* Fallback color */
background-color: rgb(242, 114, 223); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid rgb(242, 114, 223);
width: 20%;
font-family: 'Barriecito', cursive;
font-size: 2em;
text-align: center;
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
#dead {
text-align: center;
}
My x is non-responsive and neither can I click anywhere else on the screen to close it. There's no error message in Chrome developer. When I put my cursor over the x the link appears 'dead'.

Use .modal('toggle') according the docs here: https://getbootstrap.com/docs/4.0/components/modal/#modaltoggle
$('#myModal').modal('toggle');
But on the default modal behavior, when user click out the modal window (gray area) it is closed automatically, see this working here: https://jsfiddle.net/Lc8ayf9k/
Consider review the javascript and stylesheet references in your page
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

Try this
$('#myModal').modal('toggle');

If you are using Bootstrap, then the modal settings bootstrap.js file should be able to close the modal.
Here is an example of Bootstrap modal.
`<div id="myModal" class="modal fade" role='dialog'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>myModal</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" title="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>"Oh, no! You killed Benny!"<br>
"He was <span id="dead">x</span> days young"</p>
</div>
</div>
</div>
</div>`
If you need a custom JavaScript to close the modal, you can try out this script:
`<script type="text/javascript">
// Get the modal object
var modal = document.getElementById('myModal');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>`

I believe the way you attached your event listeners is wrong. If you're using vanilla javascript, you should assign the DOM inside a variable first:
var thisSpan = document.getElementById("close");
thisSpan.addEventListener("click", function(){
modal.style.display = "none";
});
With jQuery, it is a bit simpler, especially if you're using bootstrap modal plugin. You can follow the other solutions given by the fellow peers here. If it is a custom modal, then we can have a similar pattern as the previous code:
$("#close").on("click", function(){
modal.style.display = "none";
});

Related

Dynamically Create a Modal for a Note Taker App

I am working on a simple note taking app using vanilla javascript. I am trying to have the program add the note with a modal that when clicked would show the text. With what I have so far it is adding the note below the input box and along with the modal button. When I click the modal button it does nothing the first click. On the second click the text and modal button disappear.
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Note Tracker</title>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.success {
background-color: #ddffdd;
border-left: 6px solid #4CAF50;
}
</style>
</head>
<body>
<h1>Note Tracker Web App</h1>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<label for="iNote">Input Note:</label><br>
<br>
<textarea id="inote" name="inote" rows="4" cols="50">
</textarea>
<br>
<button type="button" id="btn" onclick="addNote()">Add Note</button>
<br><br>
<div id="noteList">
<span class="close">×</span>
</div>
<script src="scripts.js"></script>
</body>
Javascript is the below that creates the note and then add it along with the modal
function addNote(){
var item = document.getElementById("inote").value
var text = document.createTextNode(item)
var newItem = document.createElement("P")
newItem.appendChild(text)
document.getElementById("noteList").appendChild(newItem)
var x = document.createElement("BUTTON");
x.id = "someId";
//x.onclick ="modalOpen()";
x.onclick = function(){
var modal = document.getElementById("noteList");
var btn = document.getElementById("someId");
btn.onclick = function() {
modal.style.display = "none";
}
};
var t = document.createTextNode("Open Modal");
x.appendChild(t);
document.getElementById("noteList").appendChild(x);
var z = document.createElement("BR");
document.getElementById("noteList").appendChild(z);
var newElem = document.createElement("BR");
document.getElementById("noteList").appendChild(newElem);
}
on first time, you are just attach event listener of click, simply put x.onclick outside the function
Hopefully this one will help.
So we have the "note-list" to handle the list.
I create a modal element that can activate when we click on the "new note" button.
In here I play with opacity and z-index to show this modal. Can be better than this.
const newNote = document.getElementById('new-note'),
addNote = document.getElementById('add-note');
let myModal = document.getElementById('my-modal');
newNote.addEventListener('click', () => {
myModal.style.zIndex = 99;
myModal.style.opacity = 1;
});
addNote.addEventListener('click', () => {
let note = document.getElementById('note'),
noteList = document.getElementById('note-list');
if (note.value !== '') {
let _el = document.createElement('li');
_el.innerHTML = note.value;
let _a = document.createElement('a');
_a.innerHTML = 'delete';
_el.appendChild(_a);
noteList.appendChild(_el);
note.value = '';
myModal.style.zIndex = -1;
myModal.style.opacity = 0;
_a.addEventListener('click', (e) => {
e.target.parentNode.remove();
});
} else {
alert('note can not empty');
}
});
#my-modal {
width: 100%: height: 100%;
z-index: -1;
opacity: 0;
position: absolute;
background: rgba(0, 0, 0, 0.5);
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.modal-wrapper {
border-radius: .5rem;
background: #fff;
display: block;
padding: 1rem;
margin-top: 20%;
}
ul {
display: block;
}
#note-list li {
display: block;
margin-bottom: .5rem;
border: 1px solid #efefef;
background: #f7f7f7;
border-radius: .5rem;
position: relative;
padding: 1rem;
width: 70%;
}
#note-list li a{
position: absolute;
right: 0;
top: 0;
background: tomato;
padding: 1rem;
color: #fff;
}
.modal-wrapper * {
display: block;
margin: .5rem auto;
width: 90%;
text-align: center;
}
<h1>Note Taker App</h1>
<div class="note-wrapper">
<ul id="note-list">
</ul>
<button id="new-note">New Note</button>
</div>
<div id="my-modal">
<div class="modal-wrapper">
<label for="note">Your Note</label>
<input type="text" name="note" id="note">
<button id="add-note">add note</button>
</div>
</div>

How make a modal transition?

I'm trying to animate a modal with a transition. I'm just looking for open it slowly but i don't understand how it works...
The modal have to be open from the center of the screen or from the screen down side.
I found this code from google :
https://codepen.io/designcouch/pen/obvKxm
But it's really too complicated for me. I can't understand how adapt it with my code...
/*Ouvrir le popup stress */
// Get the modal
var hydricstressmodal = document.getElementById('hydricstressmodal');
// Get the button that opens the modal
var stress = document.getElementById("stress");
// Get the <span> element that closes the modal
var hydricstressspan = document.getElementsByClassName("stressclose")[0];
// When the user clicks the button, open the modal
stress.onclick = function() {
hydricstressmodal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
hydricstressspan.onclick = function() {
hydricstressmodal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == hydricstressmodal) {
hydricstressmodal.style.display = "none";
}
}
/*Ouvrir le popup vegetal */
// Get the modal
var vegetalmodal = document.getElementById('vegetalmodal');
// Get the button that opens the modal
var vegetal = document.getElementById("vegetal");
// Get the <span> element that closes the modal
var vegetalspan = document.getElementsByClassName("vegetalclose")[0];
// When the user clicks the button, open the modal
vegetal.onclick = function() {
vegetalmodal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
vegetalspan.onclick = function() {
vegetalmodal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == vegetalmodal) {
vegetalmodal.style.display = "none";
}
}
#charset "UTF-8";
/* CSS Document */
body {
margin: 0;
font-size: 28px;
background-color: #00011f;
display: flex;
flex-direction: column;
margin : auto;
}
/*popup hydric stress*/
.hydricstressmodal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.7); /* Black w/ opacity */
}
/* stress Modal Content */
.stress-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height: 70%;
border-radius: 30px;
overflow: scroll;
}
.popstress img{
width: 20%;
}
/* The Close Button */
.stressclose {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.stressclose:hover,
.stressclose:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/*popup Vegetal*/
.vegetalmodal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.8); /* Black w/ opacity */
scale
}
/* stress Modal Content */
.vegetal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height: 70%;
border-radius: 30px;
overflow: scroll;
}
.popvegetal img{
width: 40%;
}
/* The Close Button */
.vegetalclose {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.vegetalclose:hover,
.vegetalclose:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<div id="content">
<h3>Electrophotonique Ingénierie : Nouvelle approche de l'imagerie macroscopique par effet de couronne dans le domaine de la santé et des biotechnologies.</h3>
<div id="file" action="" class = "container">
<input id = "stress" type="image" src="IMAGES/PNG/hydricstress.png" />
<div class = "text">
Stress hydrique
</div>
</div>
<!-- The hydric stress Modal -->
<div id="hydricstressmodal" class="hydricstressmodal">
<div class="stress-content">
<span class="stressclose">×</span>
<div class ="popstress" ><img src="images/png/hydricstress.png"></div>
<p>Some text in the Modal..</p>
</div>
</div>
<div id="file" action="" class = "container">
<input id = "vegetal" type="image" src="IMAGES/PNG/vegetal.png" />
<div class = "text">
Biophotonique appliquée aux végétaux
</div>
</div>
</div>
<!-- The vegetal Modal -->
<div id="vegetalmodal" class="vegetalmodal">
<div class="vegetal-content">
<span class="vegetalclose">×</span>
<div class ="popvegetal" ><img src="images/png/vegetal.png" ></div>
<p>Some text in the Modal..</p>
</div>
</div>
<div id="file" action="" class = "container">
<img src="IMAGES/PNG/pont.png" width="100%" />
<div class = "text">
Etudes des ponts photoniques
</div>
</div>
<script type="text/javascript" src="JS/sticky_navbar.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src="js/index.js"></script>
<script src="js/button.js"></script>
A simple solution with css animations:
$('#open').click(function() {
$('#modalOverlay').show().addClass('modal-open');
});
$('#close').click(function() {
var elem = $('#modalOverlay');
elem.removeClass('modal-open');
setTimeout(function() {
elem.hide();
},200);
});
#modalOverlay {
position: fixed;
top:0;
left:0;
right:0;
bottom:0;
background-color: rgba(0,0,0,0.8);
z-index:9999;
}
#modal {
position:fixed;
width:60%;
top:55%;
left:50%;
padding:15px;
text-align:center;
background-color:#fafafa;
box-sizing:border-box;
opacity:0;
transform: translate(-50%,-50%);
transition:all 150ms ease-in-out;
}
#modalOverlay.modal-open #modal {
opacity:1;
top:50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="open" type="button">View modal</button>
<div id="modalOverlay" style="display:none;">
<div id="modal">
<h1>My modal</h1>
<p>This is a simple modal</p>
<button id="close" type="button">Close</button>
</div>
</div>
If you don't want to spend too much time on this kind of feature you could use a library like https://sweetalert2.github.io/ which is very easy to use and do the job.
You can also use library like bootstrap. For bootstrap modal you can refer below link.
https://getbootstrap.com/docs/4.0/components/modal/

How to apply CSS transition effect on a JS triggered event?

I'm new to HTML/CSS/JS.
I have an HTML form with two input fields: e-mail and favorite website. I have two regular expressions in my JS file which check the input. This works fine, but I want to trigger an error message when the user clicks out of the box(onblur event).
My problem is that I want to apply a transition effect on the error, so it becomes visible over time, not just suddenly appears. Plus, right now, the error message pops up only once.
So my questions are:
How to apply the transition effect on the error message;
How to make it appear as many times as the user fails to enter the right input.
Here is my the HTML file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="CSS2_2.css">
</head>
<body>
<div id="webpagevalidationerror" class="error">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p>Wrong website !</p>
</div>
<div id="emailvalidationerror" class="error">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<p>Wrong e-mail !</p>
</div>
<form name="myform" class = "relative">
<fieldset>
<legend>Personal information:</legend>
E-mail :<br>
<input id="email" type="text" name="email" onblur="validateEmail(this)"><br>
Favorite website :<br>
<input id="webpage" type="text" name="webpage" onblur="validateWebpage(this)"><br><br>
<input id="submit" type="submit" value="Submit">
</fieldset>
</form>
<script src="JS_2.js"></script>
</body>
And the CSS file :
fieldset {
display: inline;
}
form.relative {
position: relative;
left: 150px;
top: 150px;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
display: none;
/*transition: 2s; How to apply this transition for the .triggered attributes ?
transition-timing-function: linear;*/
}
.triggered {
display: block;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
And the Javascript file :
var emailerror = document.getElementById("emailvalidationerror");
var webpageerror = document.getElementById("webpagevalidationerror");
function validateEmail(email) {
var re = new RegExp("^[^#]+#yahoo.com$");
var re2 = new RegExp("^[^#]+#gmail.com$");
if (!(re.test(email.value)) && !(re2.test(email.value)) || email.value == "") {
emailerror.classList.toggle("triggered");
}
}
function validateWebpage(webpage) {
var re = new RegExp("^www\\.[a-zA-Z0-9_-]+\\.[a-z]+\\.[a-z]+$");
if (!(re.test(webpage.value)) || webpage.value == "") {
webpageerror.classList.toggle("triggered");
}
}
You can't animate from display:none to display:block. The trick is to set scale and opacity to 0, then trigger the opacity animation with the delay of the scale animation duration.
Also validation functions may return a boolean, to check if everything is ok when you submit your form (and you don't want to toggle triggered class, as you wish the message to be still displayed as long as the input is wrong. So just add class if it's wrong, remove it if it's ok).
And rather than set inline atributes on your HTML elements (onClick,onBlur,...), set eventlisteners in your js code (to avoid to mix js and html)
Here a working snippet adapted from your existing code:
var emailerror = document.getElementById("emailvalidationerror");
var webpageerror = document.getElementById("webpagevalidationerror");
var closeBtn = document.getElementsByClassName("closebtn");
// loop throught closeBtn nodelist to add listener for each buttons
for(var i = 0; i < closeBtn.length; i++)
{
closeBtn[i].addEventListener("click",function(e){
e.currentTarget.parentElement.classList.remove("triggered");
});
}
document.getElementById("webpage").addEventListener("blur",validateWebpage);
document.getElementById("email").addEventListener("blur",validateEmail);
document.getElementById("submit").addEventListener("click",submitForm);
function validateEmail() {
var valToTest = document.getElementById("email").value;
var re = new RegExp("^[^#]+#yahoo.com$");
var re2 = new RegExp("^[^#]+#gmail.com$");
if (!(re.test(valToTest)) && !(re2.test(valToTest)) || valToTest == "") {
emailerror.classList.add("triggered");
return false;
}
emailerror.classList.remove("triggered");
return true;
}
function validateWebpage() {
var valToTest = document.getElementById("webpage").value;
var re = new RegExp("^www\\.[a-zA-Z0-9_-]+\\.[a-z]+\\.[a-z]+$");
if (!(re.test(valToTest)) || valToTest == "") {
webpageerror.classList.add("triggered");
return false;
}
webpageerror.classList.remove("triggered");
return true;
}
function submitForm(e){
e.preventDefault();
var emailOk = validateEmail();
var webPageOk = validateWebpage();
if(emailOk && webPageOk){
document.getElementById("myform").submit();
}
}
fieldset {
display: inline;
}
form.relative {
position: relative;
left: 150px;
top: 150px;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
/* display: none;*/
/*transition: 2s; How to apply this transition for the .triggered attributes ?
transition-timing-function: linear;*/
transform-origin:50% 50%;
transform:scale(0);
opacity:0;
transition: transform .2s, opacity 2s .2s;
}
.triggered {
/* display: block;*/
transform:scale(1);
opacity:1;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}
<div id="webpagevalidationerror" class="error">
<span class="closebtn">×</span>
<p>Wrong website !</p>
</div>
<div id="emailvalidationerror" class="error">
<span class="closebtn">×</span>
<p>Wrong e-mail !</p>
</div>
<form id="myform" class = "relative">
<fieldset>
<legend>Personal information:</legend>
E-mail :<br>
<input id="email" type="text" name="email"><br>
Favorite website :<br>
<input id="webpage" type="text" name="webpage"><br><br>
<input id="submit" type="submit" value="Submit">
</fieldset>
</form>
If you just want to show it smoothly just change your triggered class
This will add a transition effect while adding the class to display it.
https://jsfiddle.net/ycLn2fyb/25/
HTML and javascript
<div id="webpagevalidationerror" class="error">
<span class="closebtn" >×</span>
<p>Wrong website !</p>
</div>
<button onClick="myFunction()"> TEST BUTTON</button>
<script type="text/javascript">
var webpageerror = document.getElementById("webpagevalidationerror");
function myFunction()
{
webpageerror.classList.toggle("show");
}
</script>
Css:
div {
position: relative;
left: 120px;
top: 130px;
width: 250px;
height: 50px;
background-color: #f44336;
color: white;
opacity: 0;
}
.show {
opacity: 1;
transition: opacity 2s ease-in;
-moz-transition: opacity 2s ease-in;
-webkit-transition: opacity 2s ease-in;
}
p {
position: relative;
left: 30px;
top: 16px;
width: 150px;
}
.closebtn {
margin-right: 25px;
margin-top: 13px;
color: white;
font-weight: bold;
float: right;
font-size: 22px;
cursor: pointer;
transition: 0.3s;
}
.closebtn:hover {
color: black;
}

Auto focus on Modal View

What I want to accomplish is auto focus on the modal view. To explain it a bit further. I want it so that when I click on my image on my web page and it opens up the modal view it should automatically focus on the modal allowing me to scroll up and down without me having to click on the image to bring it on focus to be able to scroll up and down using my keyboard.
http://imgur.com/a/hG0CF
http://imgur.com/a/W9Erw
http://imgur.com/a/Ijcn5
Follow up I gave links above to pictures. Hopefully its easier now. Cheers
HTML
<!DOCTYPE html>
<html>
<head>
<title>
Advise Column
</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="Modal.css">
<link href="https://fonts.googleapis.com/css?family=Quattrocento|Risque|Unkempt" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br/>
<div class="container">
<div class="row">
<div class="panel panel-info">
<div class="panel-heading"><h1 id="top-hd-01" class="page-header">PICK A SENSEI!</h1></div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement">
<img src="Batman.jpg" alt="BATMAN" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-01">
<figcaption class="img-captioning">BATMAN</figcaption>
</figure>
<figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement">
<img src="Robin.jpg" alt="ROBINS" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-02">
<figcaption class="img-captioning">ROBIN</figcaption>
</figure>
<figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement">
<img src="Joker.jpg" alt="JOKER" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-03">
<figcaption class="img-captioning">JOKER</figcaption>
</figure>
</div>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<!-- The Close Button -->
<span class="close" id="modal-cross-button" onclick="document.getElementById('myModal').style.display='none'">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="modal-adv-page-img">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
<script src="Modal.js" type="text/javascript"></script>
</body>
</html>
CSS
#top-hd-01
{
font-family: 'Unkempt', cursive;
}
.img-placement
{
display: block;
text-align: center;
/*cursor: pointer;*/
}
.advise-page-img-sizing
{
height: 250px;
width: 350px;
}
.img-captioning
{
font-size: 35px;
font-family: 'Risque', cursive;
text-align: center;
margin-top: 10px;
}
/* Style the Image Used to Trigger the Modal */
.adv-page-img-modalling {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
.adv-page-img-modalling:hover {opacity: 0.7;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}
/* Modal Content (Image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
padding: 20px;
/*height: 100%;*/
/* max-height: 450px;
max-width: 700px;*/
}
#modal-cross-button
{
position: fixed;
}
.sensei-answers, .sensei-questions, .sensei-quote
{
font-family: 'Quattrocento', serif;
}
.sensei-questions
{
font-size: 28px;
}
.sensei-answers
{
font-size: 22px;
color: darkblue;
}
.sensei-quote
{
font-size: 20px;
text-align: center;
color: #ff751b;
}
/* Caption of Modal Image (Image Text) - Same Width as the Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* Add Animation - Zoom in the Modal */
.modal-content, #caption {
-webkit-animation-name: zoom;
-webkit-animation-duration: 0.6s;
animation-name: zoom;
animation-duration: 0.6s;
}
#-webkit-keyframes zoom {
from {-webkit-transform:scale(0)}
to {-webkit-transform:scale(1)}
}
#keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
}
JavaScript
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var modalImg = document.getElementById("modal-adv-page-img");
var img1 = document.getElementById("adv-page-img-01")
var img2 = document.getElementById("adv-page-img-02")
var img3 = document.getElementById("adv-page-img-03")
var captionText = document.getElementById("caption");
img1.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
img2.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
img3.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
You could try this:
$("#myModal").on('shown.bs.modal', function () {
$(this).focus();
});
The autofocus attribute won't work in this case, since this will fire on page load. However, you can easily tackle this problem with some JavaScript.
document.getElementById('modal').focus(); // vanilla JS
$('#modal').focus(); // jQuery
Make sure to trigger one of these functions as soon as the modal is openend.

How do I manage multiple overlays on different buttons clicks?

function toggleOverlay_1() {
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox_1');
overlay.style.opacity = .8;
if (overlay.style.display == "block") {
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
function toggleOverlay_2() {
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox_2');
overlay.style.opacity = .8;
if (overlay.style.display == "block") {
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#specialBox_1 {
display: none;
position: fixed;
z-index: 3000;
height: 100%;
width: 100%;
background: #FFF;
color: #000;
}
div#specialBox_2 {
display: none;
position: fixed;
z-index: 3000;
height: 100%;
width: 100%;
background: #FFF;
color: #000;
}
div#wrapper {
position: absolute;
top: 0px;
left: 0px;
padding-left: 24px;
}
.closebtn {
position: absolute;
top: 0%;
right: 45px;
font-size: 40px;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="http://a.vimeocdn.com/js/froogaloop2.min.js"></script>
<div id="overlay">
<div id="specialBox">
<iframe id="myVid_1" src="https://player.vimeo.com/video/183364240?api=1&title=0&byline=0&portrait=0&player_id=myVid_1" width="100%" height="100%" frameborder="0"></iframe>
<div class="closebtn">
×
</div>
</div>
</div>
<div id="overlay">
<div id="specialBox">
<iframe id="myVid_2" src="https://player.vimeo.com/video/183364240?api=1&title=0&byline=0&portrait=0&player_id=myVid_2" width="100%" height="100%" frameborder="0"></iframe>
<div class="closebtn">
×
</div>
</div>
</div>
<div id="wrapper">
<input type="button" name="Google_Red" class="button_red" value="Google" a href="#" onclick="toggleOverlay_1()"></input>
<br>
<input type="button" name="W3Schools Red" class="button_red" value="Sealed Air" a href="#" onclick="toggleOverlay_2()"></input>
<br>
</div>
I am trying to open different videos(in an overlay) on different button clicks. I could this well if I use just one button and its opens the video correctly. But when I try to bind different videos to different buttons, it just binds one videos to all the buttons. Can someone tell me how to solve this issue?
Based on your html and jquery. Here is what you need to do. Instead of making 2 functions. Keep one function for toggle with the iframe id as parameter the toggleOverlay(playerid). As your video iframe id's parent div is the specialbox and the specialbox parent is the overlay itself. You can utilize the .parent() method of jquery to set it up.
function toggleOverlay(playerid){
$("#" + playerid).parent("#specialBox").parent().css("opacity",".8");
$("#" + playerid).parent("#specialBox").parent().toggle();
$("#" + playerid).parent("#specialBox").toggle();
}
Now in the buttons or anywhere you call the toggleOverlay function, add the unique playerid as parameter and your set based on which button handles which overlay.
Also you cant have 2 divs with same ids. So change the second overlay div id to "overlay2".
Here is working example:
http://codepen.io/Nasir_T/pen/pEmEJE
Because you are targeting the div with an ID, the DOM will take the first div with that id (your first video). So you have to target your second overlay with another ID.
Here is a rebuild option, I feel like this might be easier than making all that javascript for each video.
// This part isnt needed but I added it in case you wanted it
// Get the modals
var modal = document.getElementById('id01');
var modal2 = document.getElementById('id02');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
if (event.target == modal2) {
modal2.style.display = "none";
}
}
.modal {
z-index: 3;
display: none;
padding-top: 100px;
position: fixed;
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 {
margin: auto;
background-color: #fff;
position: relative;
padding: 0;
outline: 0;
width: 600px
}
.container {
padding: 0.01em 16px
}
.closebtn {
text-decoration: none;
float: right;
font-size: 30px;
font-weight: bold;
}
.closebtn:hover,
.closebtn:focus {
color: red;
cursor: pointer
}
<button onclick="document.getElementById('id01').style.display='block'">Open Video 1</button>
<button onclick="document.getElementById('id02').style.display='block'">Open Video 2</button>
<!-- Video 1 -->
<div id="id01" class="modal">
<div class="modal-content">
<div class="container">
<span onclick="document.getElementById('id01').style.display='none'" class="closebtn">×</span>
<iframe src="https://player.vimeo.com/video/183364240?api=1&title=0&byline=0&portrait=0&player_id=myVid_1" width="100%" height="100%" frameborder="0"></iframe>
</div>
</div>
</div>
<!-- Video 2 -->
<div id="id02" class="modal">
<div class="modal-content">
<div class="container">
<span onclick="document.getElementById('id02').style.display='none'" class="closebtn">×</span>
<iframe src="https://player.vimeo.com/video/183364240?api=1&title=0&byline=0&portrait=0&player_id=myVid_2" width="100%" height="100%" frameborder="0"></iframe>
</div>
</div>
</div>

Categories