How to append query string variable to existing URL with history.pushState?

Viewed 934

I currently have a URL which displays all of my projects:
http://localhost:8090/projects.php
When I click on one I am able to append a variable to the end of the URL with this simple code:

$(document).ready(function() { 
$(".projects-container").on("click", ".procject-listing", function(){
  history.pushState({}, '', '?info='+$(this).attr("id"));
    $(".project-info").show(); 
          });
        });

The URL becomes:
http://localhost:8090/projects.php/?info=23
Works perfectly. The problem is, when I click inside the "info" div to open another picture, I want the click function to append the picture ID to the end of the URL:

$(document).ready(function() { 
$(".photo-block").on("click", ".photo", function(){
  history.pushState({}, '', '?photo='+$(this).attr("id"));
    $(".photo-viewer").show(); 
          });
        });

I was hoping to get a url that looks like:
http://localhost:8090/projects.php/?info=23?photo=1
Instead I got:
http://localhost:8090/projects.php/?photo=1
Is there any way to append to the URL instead of overwriting the 'already-there' query string variable?
I've been looking at other questions, but they dont seem to be addressing my issue.
Thanks!!

2 Answers

Here you go boss, parse the current URL query string, make a variable, then add it into the equation. It is dynamic as you wanted for its contents are based upon the click.

$(document).ready(function() { 
  $(".photo-block").on("click", ".photo", function(){
    function query_string(variable){
       var query = window.location.search.substring(1);
       var vars = query.split("&");
          for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
              if(pair[0] == variable){
                  return pair[1];
                  }}return(false);} 
     history.pushState({}, '','?info=' + info +'?photo='+$(this).attr("id"));
     $(".photo-viewer").show(); 
          });
        });

if you want multiple querystring variables, you need to join them with a &. Thus -> projects.php?firstVar=1&secondVar=2.

Alternatively you can also use a hash # which wouldn't require you to pushstate, but rather just wrap your pictures in a normal anchor like projects.php/?info=23#photo1. The url will change when the user clicks the img

Related