I have this function which, when I click a button, another div will be shown, and another div will be hidden. The code works, but it’s sloppy. Is there any good ideas how to shorten the function down?
$(document).ready(function(){
$("#page-1-button").click(function(){
$("#page-2").css('display','inline');
$("#page-1").css('display','none');
$('html, body').animate({scrollTop:'0px'},300)
});
$("#page-2-button").click(function(){
$("#page-3").css('display','inline');
$("#page-2").css('display','none');
$('html, body').animate({scrollTop:'0px'},300)
});
$("#page-2-button-back").click(function() {
$("#page-1").css('display','inline');
$("#page-2").css('display','none');
$('html, body').animate({scrollTop:'0px'},300)
});
$("#page-3-button-back").click(function(){
$("#page-2").css('display','inline');
$("#page-3").css('display','none');
$('html, body').animate({scrollTop:'0px'},300)
})
});
<div id="page-1"> <input id="page-1-button" /> </div>
<div id="page-2"> <input id="page-2-button" /> <input id="page-2-button-back" /> </div>
<div id="page-3> <input id="page-3-button-back" /> </div>
Depending on your HTML, you may want to look at manipulating elements in relation to the button:
Not knowing your HTML structure, I’ll guess:
This way the same code can work for all of the elements using class names and relative DOM positions, without needing to make a specific call for each ID.