I have a div on my page (with set id) and a button that "opens"/"closes" it. By default this div is hidden (display: none).
Upon the click on the button I open/close the div and append or remove a hash tag to the url: window.location.hash = "#about_us_text"; or window.location.hash = ""; On each document load I check whether the hash tag is set so I can show the div right away if the URL was inputed with the hash tag:
if(window.location.hash == "#about_us_text") {
$("a[href='#about_us_text']").trigger("click"); //trigger the click event which 'slides down' the div
console.log("hash found");
}
This all works quite fine but there is a small problem I cannot resolve. If I open a new tab/window and I input the URL with or without the has, it works as intended. But if I open the page, let it load and then replace the URL within the same tab, the hash tag is not taken into consideration. E.g.:
I open www.mysite.com/index.html -> no hash, div doesn't show => correct
I replace the url in the same window/tab to www.mysite.com/index.html#about_us_text -> the page doesn't reload (document ready doesn't fire), div does not show despite the fact that it should.
Is there any way how to solve that the div is shown/displayed when the URL changes in the same window/tab? Thanks a lot!
I found this handy. original post is here
On - window.location.hash - Change?
$(window).on('hashchange', function() {
//.. work ..
});
Related
I have a web page in which my anchor tags refer to one of the elements within the same page using #id. But this changes my URL as it adds the #id into the suffix. So now when I want to go back to the page from where I came by clicking the back button of the browser, it doesn't go back to the previous page instead it goes back to the hash selections I have made by clicking the anchor tags. Please help me by giving a solution to this.
When you use a hash route it creates a new record in the browser history the same as if you navigated to a new page. So if you navigate on your site from a page to a hash route on that page, then navigate to a new page, you will have to click on the back button twice to get back to your original location.
So if you navigate https://example.com -> https://example.com#myHash -> https:/example.com/another-page then the first back button click will navigate to https://example.com#myHash and the second back button click will navigate to https://example.com
Hope that helps
You can use history.replaceState() function from History API to achieve such behavior. When user will click on anchor you will just replace current history item instead of adding a new one.
Edit: window.location.replace()
Another approach is to use window.location.replace() which is does not adds a new entry to browser's History:
The Location.replace() method replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History, meaning the user won't be able to use the back button to navigate to it.
So what can be done to achieve the desired result is to add an onclick handler on the body element with a logic inside which will replace current location if current location is not a homepage (or any other page). This handler will look similar to the code below:
function handler (event) {
if (!isAnchor(event.target) return; // return if clicked element is not an anchor (isAnchor function should be also implemented by you. For example, you can add some class on every anchor and check if clicked element is <a> tag with this class)
if (window.location.href !== window.location.origin) { // check if you are currently on the homepage
event.preventDefault(); // if not on homepage then prevent default <a> tag redirect
window.location.replace(event.target.href); // and replace current history item URL with the new URL
}
}
I have a test website www.lemonbrush.com is has the two menu items "Home" and "About".
When we click on the "About" menu, the About page is loaded dynamical, which is great, but when I type the About page's url directly http://www.lemonbrush.com/about.html into the address bar, my whole plan goes for six.
I need some guidance in how shall I structure and load the pages so that the whole header and navigation are included even when we use the direct URL in the address bar.
My skills are HTML and Javascript.
Please see the following screen shots.
When you're clicking the menu item you are updating the page with the data, but when you are going to the link directly you are just getting the data. one way around this is to have common elements for the page, ie. navigation menus, In a javascript file and then use a script tag with a link where you want it on the page.
so, since i thought it would be nice for my project, to have a usable browser history and bookmarkable subpages, i yesterday tried the approach from my comments of the OP.
step 1: change the anchors in your navigation bar to something like that:
home
about
needles to say, that they don't need to be inside the same parent element. those links could be anywhere.
step 2: remove the on click handler from your script, that reacts on the navigation bar clicks!
step 3: create a function, to listen to the onhashchange event. (this has to be done once, on the main html page)
//create a function for the onhashchange event
window.onhashchange = function()
{
//check if a location hash is used
if(window.location.hash != null)
{
//store current location hash in a variable
requestedPage = location.hash;
//remove the '#' from the location hash value
requestedPage = requestedPage.replace('#','');
//load content from subpage into your content frame
$('#contentFrame').load('./' + requestedPage + '.html', function( response, status, xhr )
{
//catch 'file not found' errors and load start page
if ( status == "error" ) {
$('#mainPanel').load('./start.html');
}
});
};
for your page, you have of course to adapt, use the correct selectors and the correct file names.
you then would call your page via www.mydomain.com, and every subdomain via www.mydomain.com/#subPage
Is it possible to capture what link on the web page the user clicked on?
Not talking about if they manually entered an url in the address bar or if they clicked on the back button - but an existing link or menu item on the current page.
This is for a commercial web page that has a standard header & footer containing links to other pages on the company's web site.
They have a complicated order form where it's not practical to try saving & restoring the state of the form.
If in the process of filling out an order the customer needs to visit another page on the web site - to review product, etc.. Ideally I would be able offer the option of opening the link in another browser window or tab instead of leaving the page so that the user doesn't loose the work they've put into the order.
I know that I could have a different set of headers & footers that are written to open their links in another window/tab but to simplify maintenance & updating I'm trying to minimize the number of variations used. Also it is possible that the user wants to abandon the order form and may get confused if in trying to do so that another window opens instead.
I am using JQuery & Javascript.
Instead of having a completely different set of headers/footers you could replace all links in certain areas with links that open in a new window like so:
$('#header a, #footer a').each(function() {
$(this).attr('target', '_blank');
});
This is what I came up with to handle this and it is working for me.
Detects when user clicks on a page link then evaluates link to determine how to handle appropriately. It does not work for links typed in the browser address bar.
I use jquery magnific-popup (http://dimsemenov.com/plugins/magnific-popup/) to create a popup window (.popupForm-handleExitRequest in my code) that offers the user the option of opening link in same window (and losing their order data), in new window or returning to order form.
$('body a').click(function(e) {
//if link is reference to page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});
I am developing a website that loads different pages depending on what menu icon a user clicks. A friend and I wrote this javascript function:
function loadPage(targetURL){
$.get( targetURL, function( data ) {
document.getElementById("placeholder").innerHTML=data;
window.scrollTo(0,0);
});
}
And the menu icons are coded like this:
<img src="images/some_icon.png" title="Some Page" onclick="javascript:loadPage('pages/somePage.php')"/>
It works great except if trying to jump to a particular div id. For example,
<img src="images/some_icon.png" title="Some Page" onclick="javascript:loadPage('pages/somePage#someLocationOnPage.php')"/>
Taking out the .scrollTo(0,0) doesn't solve the issue. I put that line in to ensure that the page is scrolled all the way up when changing pages (Otherwise, if you were in the middle of the page and clicked a menu icon, the new page would display in the middle of the page).
What have I missed? How can I get the link to jump to a div id?
The two URL's are not different. The one with the bookmark just gets the same HTML code. Since you are not telling the browser to go to a specific bookmark, it should display the same information. (Unless your server sends different info for that link, of course)
I guess you'd have to manually move the view to the bookmark you want.
function loadPage(targetURL, targetID){
$.get( targetURL, function( data ) {
document.getElementById("placeholder").innerHTML=data;
if(targetID && $("#"+targetID).length != 0){
$(document).scrollTop($("#"+targetID).offset().top);
}
else {
window.scrollTo(0,0);
}
});
}
And then give the ID for the target as another parameter. If that's not possible, you can also search for # in the url and find the ID/ or anchor.
First of all you should keep the window.scrollTo(0,0) in your code to keep the page go to top on every click of menu item.
Secondly if on click of menu icon which is calling
loadPage('pages/somePage#someLocationOnPage.php')
your intentions are to open 'somePage' and scroll to the position where element id is 'someLocationOnPage.php' then you should update your loadPage method to check for the part after '#'.
function loadPage(targetURL){
$.get( targetURL, function( data ) {
document.getElementById("placeholder").innerHTML=data;
window.scrollTo(0,0);
// Grab url part after '#'
var name = targetURL.substr( href.indexOf('#') + 1 ), target = $('a[name='+ name +']'), target2 = $('#' + name);
// Determine of bookmark is available or not
target = (target.length)? target : target2;
// Scroll to the bookmark
$('html,body').animate({
scrollTop: target.offset().top
},400);
});
}
I want to use onbeforeunload to give a message to users before leaving certain pages.
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
Thanks
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
No, definitely not. The onbeforeunload event tells you only that the page is about to be unloaded, but not why.
It depends on how the user is leaving the page.
If they are typing an url in the address bar - then you're out of luck. As far a I know there's no way to capture the url of an address bar jump.
If they are clicking on a link contained somewhere on the page - that you can use the click event to capture the url and then decide how you want to handle things.
I posed a similar question
How can i get the destination url of a link on the web page in the javascript onbeforeunload event?
because I had a project to fix a wholesale order form. During the process of filling out an order my client's customers would go back to the catalog to check on a product's detail page and loose the current information on their order form.
By using the code below (which uses JQuery though I'm sure you could create the same thing in pure Javascript if you had to) I could tell when the user clicked a link that would leave the order form and then give them the option of opening the link in a new window/tab or loading the url in the current window and loosing their form data, or just returning to the form. This code works with all of the major browsers, at least their more recent versions.
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});