Onclick change url to previous url - javascript

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.

You could always add an attribute to the div to specify which state the modal is in, something like:
<div data-modalstate="open" onclick="ChangeUrl('Case study 5','BASEURL/case_studies=case-study-5');"></div>
Then your function could simply assets the modalstate and take the appropriate action.

Related

How to create a URL on (and within) an overlay

In a web application I'm working on, when someone wants to change their search location (for a map), they click on a button which brings up an overlay... the overlay has 3 tabs: Search by Location, Variables, and Stations. What I am trying to do is have the url updated whenever the overlay is up and also change depending on which tab they are on. This way when they share the URL, the exact overlay will be shown for the other person as well.
I've tried the push/replaceState() from https://developer.mozilla.org/en-US/docs/Web/API/History_API , which updates the url; but when I close the overlay, the same url is still shown... also, when I try to go back to that same url, the overlay is not shown.
Any ideas will be appreciated. Thank you!
Code... be advised I've tried several different scenarios which is why there's commented lines
// function addURL(element) {
// $(element).attr('href', function() {
// window.location.href = window.location +"&"+ "searrch";
// // return window.location.href
// });
// }
var stateObj = { foo: "bar" };
function change_my_url()
{
// history.replaceState(stateObj, "page 2", "#search");
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
}
var link = document.getElementById('nav-search-btn');
link.addEventListener('click', change_my_url, true);

Using pushstate to load certain pages on my ajax website

I am installing a social network sharing plugin to my website and I notice that I can only share one link.... the main index link.. How would I go about using pushstate to change the url in my browser to load each specific page on my website when sharing. Becuase using my ajax code I only have one URL and thats https://trillumonopoly.com. Im not familiar with pushstate but ive read that it is what im looking for.
for example if I want to social share the page for music on my website so when people click the link it will take them to my website index page with that specific page loaded into the div. How will I do it.
heres my jquery / ajax code
$(document).ready(function () {
loadMainContent('main');
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
loadMainContent($(this).attr('href'));
});
});
function loadMainContent(page) {
$('#main').load('pages/' + page + '.php');
}
If you have a url like yoursite/someroute then you'll get a not found error. So you'll need to tell apache to serve index.php for those routes using rewrite.
In document.ready you need to check for the url (document.location.pathname) and load the content according to what the path is.
The index page should always show a loading spinner that will be replaced with the actual content based on the path name in the url
Here is some simple sample code of how you could do this:
//if path is /contact then return object with the url to php content page
// and title of the page
const pathToPage = path => {
switch (path) {
case "/contact":
return {
url:"/contact.php"
,title:"Contact"
,path:path
};
}
}
//when user navigates back and forward
window.addEventListener(
"popstate"
,event =>
//only set content, do not mess with history
onlyLoadmain(
pathToPage(location.pathname)
)
);
//load main content with or without messing with history
const loadMainBuilder = (push)=>(page)=> {
//if page is undefined then path is not of known content
if(page!==undefined){
if(push){
//set the url
history.pushState(
{},
page.title
,page.path
);
}
document.title = page.title
//#todo: should show loading here
//$('#main').html(loading);
$('#main').load(
'pages/' + page.url + '.php'
);
}
}
const loadMainAndPush = loadMainBuilder(true);
const onlyLoadmain = loadMainBuilder(false);
//... other code
$(document).ready(function () {
//load the content of current page
// when user gets a url in their email like yoursite/contact the
// apache rewrite rule will serve index.php but main content is
// showing loading untill your code actually replaces it with something
onlyLoadmain(pathToPage(location.pathname));
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
//the element clicked should have href with the path, not the php file path
//so /contacts not /pages/contacts.php
loadMainAndPush(pathToPage($(this).attr('href')));
});
});

Store data when popup loses focus

I'm developing a Chrome extension and I would like to preserve user input data when user closes the extension's popup. Is there any reliable way to do this using local storage when the extension popup loses focus?
I managed to figure that one out. When I was calling store functions directly from popup unload callback (detecting lost focus) it didn't work. Managed to do that when I was doing the storage in background page. Sample code below:
Background script:
function storeFormDataLocally(someData) {
if (someData != null) {
chrome.storage.local.set({
'someDataKey': someData
}, function() {
console.log("data saved: " + someData)
});
}
}
Popup:
addEventListener("unload", function(event) {
var background = chrome.extension.getBackgroundPage();
var someData = "My data to store";
background.storeFormDataLocally(someData);
}, true);

Window.open only if the window is not open

I have a link on my site that opens a new window to a page that plays a very long audio file. My current script works fine to open the page and not refresh if the link is clicked multiple times. However, when I have moved to a seperate page on my site and click this link again, it reloads. I am aware that when the parent element changes, I will lose my variable and thus I will need to open the window, overiding the existing content. I am trying to find a solution around that. I would prefer not to use a cookie to achieve this, but I will if required.
My script is as follows:
function OpenWindow(){
if(typeof(winRef) == 'undefined' || winRef.closed){
//create new
winRef = window.open('http://samplesite/page','winPop','sampleListOfOptions');
} else {
//give it focus (in case it got burried)
winRef.focus();
}
}
You should first to call winRef = window.open("", "winPopup") without URL - this will return a window, if it exists, without reloading. And only if winRef is null or empty window, then create new window.
Here is my test code:
var winRef;
function OpenWindow()
{
if(typeof(winRef) == 'undefined' || winRef.closed)
{
//create new
var url = 'http://someurl';
winRef = window.open('', 'winPop', 'sampleListOfOptions');
if(winRef == null || winRef.document.location.href != url)
{
winRef = window.open(url, 'winPop');
}
}
else
{
//give it focus (in case it got burried)
winRef.focus();
}
}
It works.
Thanks to Stan and http://ektaraval.blogspot.ca/2011/05/how-to-set-focus-to-child-window.html
My solution creates a breakout pop-up mp3 player that remains active site wide and only refreshes if the window is not open prior to clicking the link button
function OpenWindow(){
var targetWin = window.open('','winPop', 'sample-options');
if(targetWin.location == 'about:blank'){
//create new
targetWin.location.href = 'http://site/megaplayer';
targetWin.focus();
} else {
//give it focus (in case it got burried)
targetWin.focus();
}
}
Like you said, after navigating away from original page you're losing track of what windows you may have opened.
As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.

Open URL in certain Tab with Dojo

I have the following function where I attempt to load a specified url into a new or existing tab (contentPane), I have it working for the most part, however when an existing tab is specified the original url still gets reloaded instead of adding the new html, how can I accomplish the part where an existing tab is passed without having to remove the attribute refreshOnShow upon creating a new tab??
openTab = function(url,title, id){
var tab = dijit.byId(id);
var centerPane = dijit.byId('centerPane');
if (tab){
//if target container exists then let's load the url and add it to the container
centerPane.selectChild(tab);
$.get(url, function(data) {
$('#'+id).html(data);
});
centerPane.selectChild(tab);
} else {
var newTab = new dijit.layout.ContentPane(
{
'title': title,
href:url,
closable:true,
selected:true,
parseOnLoad:true,
preventCache:true,
refreshOnShow:true
}, id);
centerPane.addChild(newTab);
centerPane.selectChild(newTab);
}
};
So what you are doing is basically saying, when this tab is re-opened, let me append my content, and dojo is saying, 'I just opened this tab, and refreshOnShow is true, so let me go get my content from the server again'.
I think the cleanest way to get around that is to do as you say and set refreshOnShow to false. Why do you have it set to true, does the tab have content that needs to be refreshed consistently from the server?
If what you want is something like this (for an existing tab):
User clicks
Dojo goes and refreshes existing tab content
Your manual (jquery based) handler goes and gets some other content
and appends it to (or otherwise uses it with) the content dojo
automatically refreshed
Then you should be able to do something like this:
newTab.connect(newTab, 'onLoad', function(){
// do my stuff after the dojo content has loaded
})
Which just adds an event handler to the contentpane for your tab that fires after the tab has gone to the server for its content.
This is how my updated function looks, it works for me:
openTab = function(url,title, id){
var tab = dijit.byId(id);
var centerPane = dijit.byId('centerPane');
if (tab){
//if target container exists then let's load the url and add it to the container
tab.href = url;
tab.set('title',title);
centerPane.selectChild(tab);
} else {
var newTab = new dijit.layout.ContentPane(
{
'title': title,
href:url,
closable:true,
selected:true,
parseOnLoad:true,
preventCache:true,
refreshOnShow:true
}, id);
centerPane.addChild(newTab);
centerPane.selectChild(newTab);
}
};

Categories