javascript - Multiple Modals One Script -


i have around 40 different modals on same page, , rather having scrip line each, trying create way use 1 script run whole thing. started code worked display 1 @ time, tried re work time link clicked updates code , correct modal displayed.

js fiddle

i found others on here, didn't seem answer why mine wasn't working. new javascript, appreciated.

  var modal = "",   lnk = "",   lnknumb = "",   modalid = "",   lnkid = "",   span = document.getelementsbyclassname("close")[0];  $('[class^="lnk"]').on('click', function(e) {   e.preventdefault();   lnknumb = this.classname.replace('lnk', '');   lnkid = ('lnk' + lnknumb);   lnk = document.getelementbyid(lnkid);   modalid = ('modal' + lnknumb);   modal = document.getelementbyid(modalid); });  // when user clicks link, open modal  lnk.onclick = function() {   modal.style.display = "block"; }  // when user clicks on <span> (x), close modal span.onclick = function() {   modal.style.display = "none"; }  // when user clicks anywhere outside of modal, close window.onclick = function(event) {   if (event.target == modal) {     modal.style.display = "none";   } } 

the content displaying in modal have @ least 1 header, , anywhere 1 6 paragraphs below that. need able style , format each of them using styles , tags.

i make single modal element populate it's content dynamically based on json object (css can stay same). when link clicked, '.modal-btn' click listener gets link's data-modal-id attribute, uses attribute access 'modaldata' json object , it's relative data:

html:

<a id="btnb12" class="modal-btn" data-modal-id="b12" href="#">b12</a> <a id="btnb02" class="modal-btn" data-modal-id="b02" href="#">b02</a>   <!-- single modal --> <div class="modal">   <!-- modal content -->   <div class="modal-content">     <span class="close">×</span>     <h2 class="modal-header"></h2>     <p class="modal-body"></p>   </div> </div> 

js:

var modaldata = {   "b12": {     "header":"modal b12",     "body":"here's text modal b12"   },   "b02": {     "header":"modal b02",     "body":"here's text modal b02"   } }  //open modal $('.modal-btn').on('click', function(e) {   e.preventdefault();   var modalid = $(e.currenttarget).data('modal-id');   $('.modal-header').text(modaldata[modalid].header);   $('.modal-body').text(modaldata[modalid].body);   $('.modal').show(); });  //close modal $('.close').on('click', function(e){     $('.modal').hide(); }); 

the json object obtained via ajax call instead, if wanted modal might based off external api's json data.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -