How to duplicate this jQuery function

2

As you may be seeing in this example fiddle , when the first link is clicked a div appears and when you press the back button of the browser, it closes. I would like the second link to work in the same way, showing the div two, but when I try to duplicate the function one of the two stops working and I have no idea why (I am a layman in JS / Jq). Can you help me?

Fiddle Link: link

Code:

$(document).ready(function() {
  $('body').on('click touch', '#paginaUm', function(e) {
    $('.pagina.um').fadeIn();
  });
});

// geri butonunu yakalama
window.onhashchange = function(e) {
  var oldURL = e.oldURL.split('#')[1];
  var newURL = e.newURL.split('#')[1];

  if (oldURL == 'paginaUm') {
    $('.pagina.um').fadeOut();
    e.preventDefault();
    return false;
  }
  //console.log('old:'+oldURL+' new:'+newURL);
}
.pagina{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:gray; color:white; padding:20px;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ahref="#paginaUm" id="paginaUm">Pagina 1</a>
  <div class="pagina um">
  <h1>Popup 1</h1>
  <p>Pressione voltar para fechar.</p>
</div>

<a href="#paginaDois" id="paginaDois">Pagina 2</a>
  <div class="pagina dois">
  <h1>Popup 2</h1>
  <p>Pressione voltar para fechar.</p>
</div>
    
asked by anonymous 11.12.2018 / 23:40

1 answer

4

I can not say exactly if this is the best practice, but if you do a click event for every btn you can duplicate the good code

See the example, test in your environment by clicking on the btn back that will work right, or right here, or at this link link

a>

$(document).ready(function() {
  $("#paginaUm").click(function(event){
    $('.pagina.um').fadeIn();
  });
  $("#paginaDois").click(function(event){
    $('.pagina.dois').fadeIn();
  });
});

// geri butonunu yakalama
window.onhashchange = function(e) {
  var oldURL = e.oldURL.split('#')[1];
  var newURL = e.newURL.split('#')[1];

  if (oldURL == 'paginaUm') {
    $('.pagina.um').fadeOut();
    e.preventDefault();
    return false;
  }
   if (oldURL == 'paginaDois') {
    $('.pagina.dois').fadeOut();
    e.preventDefault();
    return false;
  }

  //console.log('old:'+oldURL+' new:'+newURL);
}
.pagina{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:gray; color:white; padding:20px;
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script><ahref="#paginaUm" id="paginaUm">Pagina 1</a>
  <div class="pagina um">
  <h1>Popup 1</h1>
  <p>Pressione voltar para fechar.</p>
</div>

<a href="#paginaDois" id="paginaDois">Pagina 2</a>
  <div class="pagina dois">
  <h1>Popup 2</h1>
  <p>Pressione voltar para fechar.</p>
</div>
    
11.12.2018 / 23:49