Corey Child Corey Child - 2 months ago 8
jQuery Question

Virtual "Back Button" jquery

I am creating a mobile web app, I have a login/ signup page where users can choose the method they want.
In order to reduce the refresh rate of pages I am hiding and showing objects depending on what the user clicks with jquery.

I have virtual back buttons on each of the 'pages' which hide/show the objects including the back buttons themselves, each time I need to add an extra 'page' I have to add and call the different buttons.

Is there a way I can have one button and use that depending on what elements are hidden/shown?

e.g

html

<div id="go_button"</div>
<div id="next_button"</div
<div id="backbutton1"</div>
<div id="backbutton2"</div>


<div id="page1"
<p> some information here </p>
</div>

<div id="page2"
<p> some more information here </p>
</div>


jQuery

$("#gobutton").click(function(){
$('#backbutton1').fadeIn(250);
$('#page1').fadeIn(250);
$('#next_button').fadeIn(250);
});

$('#next_button').click(function(){
$('#backbutton1').hide();
$('#backbutton2').show();
$('#page1').fadeOut(250);
$('#page2').fadeIn(250);
$('#next_button').fadeOut(250);


$("#backbutton1").click(function(){
$('#backbutton1').fadeOut(250);
$('#page1').fadeOut(250);
$('#next_button').fadeOut(250);
});


etc etc

Answer

Would something like this work for you?

I checked the currently visible page, and based on that and what button is clicked, it would go forward or back.

var
  $go = $('#go_button'),
  $next = $('#next_button'),
  $back = $('#backbutton'),
  $pages = $('div[id^=page]');

$go.click(function() {
  $next.fadeIn(250);
  $back.fadeIn(250);
  $pages.first().fadeIn(250);
});

$next.click(function() {
  var $current = $pages.filter(':visible'); // Get currently visible page

  if (!$current.is($pages.last())) { // If this is not the last page, do something
    $current
      .hide() // hide current page
      .next() // get next page
      .fadeIn(250); // fade in next page
  }
});

// Opposite of the $next.click
$back.click(function() {
  var $current = $pages.filter(':visible');

  if (!$current.is($pages.first())) {
    $current
      .hide()
      .prev()
      .fadeIn(250);
  }
});
div[id^=page] {
  padding: 5px 10px;
  border: 1px solid #ddd;
  display: none;
}

#next_button,
#backbutton {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="go_button">go</button>
<button id="next_button">next</button>
<button id="backbutton">back</button>

<div id="page1">
  <p> 1 some information here </p>
</div>
<div id="page2">
  <p> 2 some more information here </p>
</div>
<div id="page3">
  <p> 3 more information here </p>
</div>
<div id="page4">
  <p> 4 more! more! more! more!</p>
</div>