1

I have referred to w3school to create a modal box. It works well, but there is one issue. It only works with 1 modal box. Let's say the page has two modal boxes. I will call it modal1 and modal2. I am trying to see if I can create a modal box without having to write the same javascript code twice for each modal box..

The HTML and CSS as follows:

<!DOCTYPE html>
<html>
<head>
<style>
/* 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 {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}
/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}
@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}
/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}
.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
</style>
</head>


<body>

<p>this is the section for testing modal box</p>

<!-- Trigger/Open The Modal -->
<button id="myBtn1">Open Modal</button>
<button id="myBtn2">Open Modal</button>


<!-- The Modal 1 -->
<div id="myModal1" class="modal">  
  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>FIRST Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 1</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3> FIRST Modal Footer</h3>
    </div>
  </div>
</div>



<!-- The Modal 2 -->
<div id="myModal2" class="modal">
  <!-- Modal content 2 -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>SECOND Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 2</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>SECOND Modal Footer</h3>
    </div>
  </div>
</div>

<script>
var modal = document.getElementById('myModal1');

var btn = document.getElementById("myBtn1");

var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal 
btn.onclick = function() {
    modal.style.display = "block";
}

// 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>  
</body>
</html>

So how would I go about opening the second modal box triggered by button myBtn2 and open the second one without having to create another same javascript code?

1
  • Have you tried using jquery .each() for this? You can loop through all the modal class elements and set the desired code of each modal it finds. Commented Nov 29, 2016 at 16:34

3 Answers 3

3

Working fiddle.

Since you're able to use jquery you could use general classes with data-* attributes :

$('.my-btn').on('click', function(){
  $('#'+$(this).data('modal')).css('display','block');
})

$('.close').on('click', function(){
  $('.modal').hide();
})

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target.className == 'modal') {
    $('.modal').hide();
  }
}

By giving your buttons the same class (my-btn in my example) you could attach event to the class one time and store the related modal id in the data attributes (data-modal in my example) then when the button is clicked retrieve the id and show the modal.

Hope this helps.

    $('.my-btn').on('click', function(){
      $('#'+$(this).data('modal')).css('display','block');
    })

    $('.close').on('click', function(){
      $('.modal').hide();
    })

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
      if (event.target.className == 'modal') {
        $('.modal').hide();
      }
    }
.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 {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
}
/* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0} 
    to {top:0; opacity:1}
}
@keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
}
/* The Close Button */
.close {
    color: white;
    float: right;
    font-size: 28px;
    font-weight: bold;
}
.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
.modal-header {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
    padding: 2px 16px;
    background-color: #5cb85c;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>this is the section for testing modal box</p>

<!-- Trigger/Open The Modal -->
<button class="my-btn" data-modal='myModal1'>Open Modal</button>
<button class="my-btn" data-modal='myModal2'>Open Modal</button>


<!-- The Modal 1 -->
<div id="myModal1" class="modal">  
  <!-- Modal content -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>FIRST Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 1</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3> FIRST Modal Footer</h3>
    </div>
  </div>
</div>



<!-- The Modal 2 -->
<div id="myModal2" class="modal">
  <!-- Modal content 2 -->
  <div class="modal-content">
    <div class="modal-header">
      <span class="close">×</span>
      <h2>SECOND Modal Header</h2>
    </div>
    <div class="modal-body">
      <p>Some text in the Modal Body 2</p>
      <p>Some other text...</p>
    </div>
    <div class="modal-footer">
      <h3>SECOND Modal Footer</h3>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

I suggest you to use class name and document.querySelectorAll. For two buttons add data-id attribute(which refers to the modal id).

<button id="myBtn1" class="modal-open" data-id="#myModal1">Open Modal1</button>
<button id="myBtn2" class="modal-open" data-id="#myModal2">Open Modal2</button>

<style>
  .modal.open {
    display: block;
  }
</style>

<script>
   var btns = document.querySelectorAll('.modal-open');
   btns.addEventListener('click', function() {
     var modalId=this.getAttribute('data-id');
     document.querySelector(modalId).classList.add('open');
   });
</script>

This code only covers the changes you need to make.

Comments

1

If you wish to try a different attack instead of W3 version, I use this one often. It is responsive and easy to customize:

		// Popup Window
		var scrollTop = '';
		var newHeight = '100';

		$(window).bind('scroll', function() {
		   scrollTop = $( window ).scrollTop();
		   newHeight = scrollTop + 100;
		});

		$('.popup-trigger').click(function(e) {
  		 e.stopPropagation();
		 if(jQuery(window).width() < 767) {
		   $(this).after( $(this).nextAll('.popup:first') );
		   $(this).nextAll('.popup:first').show().addClass('popup-mobile').css('top', 0);
		   $('html, body').animate({
				scrollTop: $(this).nextAll('.popup:first').offset().top
			}, 500);
		 } else {
			 $('.popup').hide();
			 $(this).nextAll('.popup:first').removeClass('popup-mobile').css('top', newHeight).toggle();
		 };
		});

		$('html').click(function() {
		 $('.popup').hide();
		});

		$('.popup-btn-close').click(function(e){
		  $(this).parent().hide();
		});

		$('.popup').click(function(e){
		  e.stopPropagation();
		});
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600,700');

			*, *:before, *:after { margin: 0; padding: 0; box-sizing: border-box; }
			body { background: #2F2556; color: #B9B5C7; font: 14px 'Open Sans', sans-serif; }

			/* You can safely remove the next two lines */
			.top { padding-right: 20px; background: #261F41; text-align: right; }
			a { color: rgba(255,255,255,0.6); text-transform: uppercase; text-decoration: none; line-height: 42px; }

			h1 { padding: 60px 0; font-weight: 400; text-align: center; }
			p { margin: 0 0 20px; line-height: 1.5; }

			.main { margin: 0 auto; padding: 40px 20px; max-width: 960px; font-size: 19px; line-height: 30px;}
			.main a { color: #DB7580; text-transform: none; }

			/* Styling the Popup Window */
			.popup-trigger { display: block; margin: 0 auto; padding: 20px; max-width: 260px; background: #4EBD79; color: #fff;
    						 font-size: 18px; font-weight: 700; text-align: center; text-transform: uppercase; line-height: 24px; cursor: pointer; }
		  	.popup {display: none; position: absolute; top: 100px; left: 50%; width: 700px; margin-left: -350px; padding: 50px 30px;
  					background: #fff; color: #333; font-size: 19px; line-height: 30px; border: 10px solid #150E2D; z-index: 9999;}
  			.popup-mobile {position: relative; top: 0; left: 0; margin: 30px 0 0; width: 100%;}
  		    .popup-btn-close {position: absolute; top: 8px; right: 14px; color: #4EBD79; font-size: 14px; font-weight: bold; text-transform: uppercase; cursor: pointer;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="popup-trigger" rel="nofollow">Popup Madrid</a>
		<div class="main">
			This is a version of the Simple Responsive Popup Window that allows you to add more than one (unlimited) number of popups while keeping the code clean and simplified. Resize your browser to test how it behaves on mobile. <br><br>
			The functionality is very basic, so you would probably have to built upon it regarding your project needs. To <a href="http://stanhub.com/multiple-responsive-popup-windows-on-same-page/">download this demo</a>, please go to the main article on Stanhub.
		</div>
		<div class="popup">
			Madrid is a city in Europe and the capital and largest city of Spain. The population of the city is almost 3.2 million and that of the Madrid metropolitan area, around 6.3 million. <br><br>
			It is the third-largest city in the European Union, after London and Berlin, and its metropolitan area is the third-largest in the European Union after Paris and London. The city spans a total of 604.3 km2 (233.3 sq mi).
			<span class="popup-btn-close">close</span>
		</div>

		<a class="popup-trigger" rel="nofollow">Popup Rome</a>
		<div class="popup">
			Rome is a city and special comune (named Roma Capitale) in Italy. Rome is the capital of Italy and of the Lazio region. With 2.9 million residents, it is also the country's largest and most populated comune and fourth-most populous city in the European Union by population within city limits. <br><br>
			Vatican City is an independent country within the city boundaries of Rome, the only existing example of a country within a city: for this reason Rome has been often defined as capital of two states.
			<span class="popup-btn-close">close</span>
		</div>

I cannot take credit for this code but use it very often and it is from this site.

Here is a JSFiddle.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.