So I have a page, with a link on it that opens a custom modal window that I built. I created an onclick method to handle a url change so that a user can save the url and open the modal page directly if they want. And then the idea would be when you close the modal, it returns to it's previous url.
HTML
<div onclick="ChangeUrl('Case study 5', 'BASEURL/case_studies=case-study-5');" ></div>
JS
function ChangeUrl(title, url) {
var address = window.location.href;
alert(address);
if (typeof (history.pushState) != "undefined") {
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
} else {
alert("Your Browser does not support HTML5. Please update your browser
to get the full experience of our website.");
}
This works great, but the problem is I am using the same onclick method to change the url when the modal is closed. Which would be fine if I was only doing this from one main page, but the modal window php file is being accessed from multiple pages to use as a modal, so I need some dynamic way to change the url back to the previous page's url. Is there any way to grab the url and put it into the onclick method in my modal php so that it will return to the previous page?
EDIT
On robmarston's advice I changed my modal html to include a data attribute called modalstate, which is set to open.
I then updated the JS to take into account the state of the attribute like so.
JS
function ChangeUrl(title, url) {
if (typeof (history.pushState) != "undefined") {
console.log($('.js-post-close').data('modalstate'));
if($('.js-post-close').data('modalState') == "open"){
var obj = { Title: "blueleaf", Url: address};
history.pushState(obj, obj.Title, obj.Url);
}
else {
address = window.location.href;
var obj = { Title: title, Url: url };
history.pushState(obj, obj.Title, obj.Url);
}
} else {
alert("Your Browser does not support HTML5. Please update your browser to get the full experience of our website.");
}
console.log(address);
}
This does not work, even thought the console will log "open" whenever I click to close the window. I also tried using $('.js-post-close').data('modalState') != undefined), but with the same result. The page will not enter the appropriate logic to change the url back to address.