Reputation: 125
I'm new to programming so please bear with me. I have a single button where when you click it, it'll go to another HTML file, but when I click it again, it won't go back to the other HTML file it was previously on. Essentially I want to toggle between the two (or more if I add additional pages).
Trying to do this only with jQuery.
$(".button").on("click", function() {
if(window.location.href = "index1.html"){
window.location.replace("index2.html");
}
});
$(".button").on("click", function () {
if (window.location.href = "index2.html") {
window.location.replace("index1.html");
}
});
This seems overcomplicated for a task like this. Any help would be appreciated!
Upvotes: 0
Views: 392
Reputation: 561
Based on your recent comment clarifying your requirement, I believe you want to maintain an array of pages, and progress to the next page with the same event using a for loop.
var pages = ['index1.html','index2.html','index3.html','index4.html'];
$(".button").on("click", function() {
for(var i = 0; i < pages.length; i++){
if(window.location.pathname == pages[i]){
if(i == pages.length - 1){
//at the end, go to first page
window.location.href=pages[0];
}
else{
window.location.href=pages[i+1];
}
break;
}
}
});
Though do debug this code and check the values for window.location - it might not be what you expect if you have a long path. You'll need to add the entire relative path (some/path/index1.html
) to the array if you wish this to work on URLs like the following www.foo.com/some/path/index1.html
.
Upvotes: 0
Reputation: 516
If these two blocks of code are in the same file, the second onclick
event is overriding the first. window.location
might also be enough if you just need to redirect.
Try this:
$(".button").on("click", function() {
if(window.location.href == "index1.html"){
window.location="index2.html";
}else if(window.location.href == "index2.html"){
window.location="index1.html";
}
});
Upvotes: 1