Okay, here is my situation.

I am creating an image gallery. So there is the main page and then lots of smaller images on the page. The URL is currently 'http://www.domain.com/gallery.php?u=x' where u is the id of the user. When a user clicks an image I am using pushState to change the URL so that it now has 'u=x&p=y' where p is the id of the image to display. this then loads up the image into an overlay which comes in the middle of the page. The change in the URL parameters is mainly there to allow me to copy the URL and then paste and still be able to access the image. (i'm not using hashes because I don't want constant reloading)

However, my issue arises when using the back button. Say a user is viewing at 'u=2&p=53' and they press back to go to 'u=2', the overlay with the image remains in place while the main page changes.

How can I deal with this? Any help with how to handle history and the back button?