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);
});
}
Related
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
I have a jQuery script that loads content into a div. When you click on a menu item, the content gets loaded inside of "contentarea" and the URL gets updated. That part works perfectly. However, I would also like to be able to click inside of the div (once content has been loaded into it), and load another page in its place. For example, the Forms page gets loaded into contentarea, and inside of the forms page there is a link to the contact us page. When I click on the link, I would like for the forms page to be cleared from content area and the contact us page to be loaded in its place. See the following image:
With the way my script is setup right now, content only loads when I click from outside of the div.
Here's the code I need to modify:
<script type="text/javascript">
//Jquery loader
function getHash() {
return window.location.hash
}
$("a").on("click", function (e) {
page = this.href.replace("#", "") + ".html",
hash = $(this).prop("hash");
$('#contentarea').load(page, function () {
if (page.match("home.html")) {
history.pushState('', document.title, window.location.pathname);
} else {
location.hash = hash;
};
});
});
//on pageload
history.pushState
var hash = getHash();
if (hash) {
$("a[href='" + hash + "']").trigger("click");
} else {
$("a[href='#home']").trigger("click");
}
</script>
Any help would be greatly appreciated!
Since you are using jQuery, i would propose this:
$(document).ready(function() {
$(document).on( 'click', 'a', function( e ) {
$('#contentarea').load( e.target.href );
});
});
But if you are creating an app, and you are applying it globally, in your case i would reconsider your structure to avoid major changes on your code later. I've passed on that, because you have to manage states (variables of page/state if they exist: like errors, title, url, and obviously content) and determine which of them is active or not to pass to next page or not. Then you have to filter links that you don't want to propague to your history states handler cause you just don't want to...
On some cases, you can't apply existent frameworks on your project because the best approach is to use their code on your framework (yes, create your own framework).
I hope this could help you! :)
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 ..
});
I need help with a jQuery function that will allow me to use hashtags to scroll to an anchor point on a .load() page.
Basically someone clicks on a homepage link and it opens up a model window that they use to navigate the remainder of the website. This window then uses the same code to open up any other links on the site. I know the format of these links is not optimal, but it's what I am required to work with.
I have the following code that is displayed in a model window.
<div id="pop-top-menu">
<p class="p_text">
Go Back |
View by Resorts |
View our Private Homes |
View our Properties with Discount Coupons</p>
</div>
When someone clicks on one of those links, it will then go though this code:
function pop(id) {
$("#body-cover").fadeIn(1000);
$("#slide-content").load(id).slideDown(1000);
$("#slide-content-close").delay(2000).fadeIn(1000);
}
So I need to have the visitor click on properties.php#property_id and it load the page properties.php and THEN navigate to the anchor tag. Not all links will have anchors, but many will.
Please note, this is not anchor-based navigation. This is loading a link and THEN navigating to the anchor provided (if it exists).
Untested, but when I understood your question correctly you could modify your pop function like this:
function pop(id) {
// Expression to test if id has a hashtag
var hasHash = /(#([^ ]*)/,
$hashID;
$("#body-cover").fadeIn(1000);
$("#slide-content").load(id).slideDown(1000);
$("#slide-content-close").delay(2000).fadeIn(1000);
if(hasHash.test(id)!== false) {
// hasfound - grep it, and make a jQuery Object
$hashID = $('#' + id.split('#')[1]);
if($hashID.length) {
// if it is found, scroll to this element with an animation
// in case you just want a jump, simply set scrollTop
// and remove the animate method
$('html, body').animate({
scrollTop: $hashID.offset().top
}, 2000);
}
}
}
When you visit http://www.rdio.com/#/aboutus/ for instance you will see that their about us page loads, now when you hover over or inspect the "About Us" link in their footer, it simply points to /aboutus. I have also checked View Source and there is strictly no magic occuring on the link itself.
I am thinking jQuery must update all their <A> elements and replace with the anchor based hash tag url approach.
How would I get this to function in my own project?
Thanks.
The anchors are there for linking; the real magic is Ajax and other dynamic JavaScript-based content. Here's what the link might look like:
$('.some-link').click(function(e) {
// Allow for linking:
window.location.hash = '#/' + this.getAttribute('href');
// Start loading the content:
$.ajax({
// ...
success: function() {
// New content gets put in
}
});
// Prevent the real link from being followed:
e.preventDefault();
});