How to reload div content on click - javascript

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! :)

Related

Got some trouble Implementing History.js for the site i am creating

I came across history.js as a possible solution to some issues i am having. For the website i am building i decided to create a static page where my content would be loaded into. So i would have 3 Divs, (one for the header, one for the menubar and one for the content) When clicking a link in the menu that page would be loaded into the content div. Because of this all traffic stays in the index.php page so clicking on the back button i would go to the last visited content but last visited page. Its my understanding i can solve this with history.js.
So on my page i have several links in the menu bar where onclick a function is called upon. For instance
<li><a href="javascript:void(0);" onclick="myprofile()" ><span>my profile</span></a></li>
<li><a href="javascript:void(0);" onclick="mysettings()"><span>Settings<small>
A function would look something like this.
function myprofile() {
$('#content').load('members.php');
}
function mysettings() {
$('#content').load('settings.php');
}
I added some javascript for history.js (found on this forum) And although it does change the urls inside my index.php but when clicking back it doesnt load the pages. How would i let history.js work when functions are used? (some links i do really need functions so just putting the onload inside link would not be an option for me)
<script>
$(function() {
// Prepare
var History = window.History; // Note: We are using a capital H instead of a lower h
if ( !History.enabled ) {
// History.js is disabled for this browser.
// This is because we can optionally choose to support HTML4 browsers or not.
return false;
}
// Bind to StateChange Event
History.Adapter.bind(window,'statechange',function() { // Note: We are using statechange instead of popstate
var State = History.getState();
$('#content').load(State.url);
/* Instead of the line above, you could run the code below if the url returns the whole page instead of just the content (assuming it has a `#content`):
$.get(State.url, function(response) {
$('#content').html($(response).find('#content').html()); });
*/
});
// Capture all the links to push their url to the history stack and trigger the StateChange Event
$('a').click(function(evt) {
evt.preventDefault();
History.pushState(null, $(this).text(), $(this).attr('onclick'));
});
});
</script>
The first parameter of the History.pushState is "data", which is for additional information.
So to save the History entry you could do this in your click event:
History.pushState({ href: 'members.php' }, $(this).text(), $(this).attr('onclick'));
And then when reading it back out you would do this in your History.Adapter.bind function:
$('#content').load(State.data.href);

How can I detect page navigation without reloading?

I have script, what work one time when window loaded, it work on this page, but site use some navigation links what not fully reload page (see this answer for example: Modify the URL without reloading the page). How can I detect that and run my script again?
I have one idea: storing URL (without anchor) in variable and check it periodically with current url, but I think this is bad solution. May be you know better one?
JavaScript or JQuery is possible to use.
Use window.onpopstate or window.onpushstate if u are using pushState or replaceState ( from ur given example).
ex:-
To Navigate Without reload ( you already did this )
// Your code to fetch new URL body and title
// update the DOM then use following code to update URL also (don't use location.href, otherwise the page reloads)
// sorry u already know this because u provided the example ;)
let data = { title : "Current Title",
body : document.body.innerHTML" } // to store current page data
window.history.pushState(data, 0, "newURL");
To detect navigation ( i.e., you wanna do )
window.onpushstate: when above code runs for navigation to a new url and load new content without reload ...
window.onpushstate(function() {
// detects ur navigation
})
window.onpopstate: when you press back button
window.onpopstate(function (e) {
let { data } = e.state;
// data object that u gave in pushState method when u called ur last / latest pushState method...
// use this data to retrieve previous data content and title
let { title, body } = data;
document.title = title;
document.body.innerHTML = body
})
for more detail mdn docs
That's because the new pages are either
1 ) Already at the ready and simply being brought in-sight by jQuery
2 ) Ajax called in.
If you scout for your navigation (the links you click on to go to the other page), you should find click me or so.
If you look for wherever this is is bound (i.e.: $('#navigation a').on("click", function(){});, you can simply wrap your script within a function, and trigger this function together with loading the new page every time. (after it, obviously).
I wish I could be more clear, but you did not provide any code yourself, so I have absolutely no idea of what kind of example I should be giving here.
-- the point: Those page changes are triggered by something in your javascript. Find the trigger that makes the page-change happen, and simply insert myCustomFunction();.
If you want to make your bindings update with a new DOM, you could use this:
function setBindings(){
//removing the old bindings prevents the "click" from triggering twice.
$('a').off("click");
$('a').on("click", function(){
//load page and such here
//Apply script you want to run here
setbindings(); //rerun the function to set the bindings.
});
}
I think you are looking for hashchanges you can listen to this event onhashchange
window.onhashchange = function(e) {
var sublink = window.location.hash.substring(1);
//do your thing here
}
You can also check what updated the url after the hashchange
var sublink = window.location.hash.substring(1);
I think the URL of script is cached,do you used Ajax get method?if it is,please
like this write url "wwww.baidu.com?"+Math.random();if not is ,in the firefox ,you can used pageshow event.

Display Proper URL in Address Bar

I'm using Jquery/Ajax to load html pages into a div on my website. I get links certain class to open up in the specified div. When doing this the address bar remains www.example.com. Due to the fact that I do have several pages that I will like to be able to share; so when people visit the links it will take them to the website but with the specific page loaded into the div container.
Here's a few lines of my code
$( document ).ready(function() {
$.ajax({
method: 'GET',
url: "pages/promo.html",
success: function(content)
{
$('#contentarea').html (content);
}
});
});
$('.menu_nav') .click (function () {
var href = $(this) .attr('href');
$('#contentarea').hide() .load(href).slideDown( 'very slow' )
return false;
});
Unless the other pages are on your domain, you cannot do this. If the other pages are, see this StackOverflow question: Updating address bar with new URL without hash or reloading the page.
Here's the deal: since you are loading a new page and you want the URL of the browser to point to that page, you should just give users a link. They know how to use the back button. (You could use the information in the linked answer to to change the URL to something like this: http://www.trillumonopoly.com/other-website.com.)
You can use the history object.
$('#contentarea').html(content);
history.pushState({url: "pages/promo.html"}, "", "pages/promo.html");
With the use of the state {url: "pages/promo.html"} you can load your page into your div when your users navigate back/forward.
$(window).on("popstate", function(e) {
if (e.originalEvent.state != null)
{
// AJAX load e.originalEvent.state.url
}
})

jquery fail on DOM modify made with html()

In my website, I build the page navigation based on hashchange:
var hashHome;
$(window).bind( 'hashchange', function(e) {
var homeClass = "home";
var url = $.param.fragment();
if($('#page-content').hasClass(homeClass)){
hashHome = $('#page-content').html();
}
if(url ==''){
//homepage with nothing(no hash)
if(!$('#page-content').hasClass(homeClass)){
//alert("load frim cache ->#"+url);
$('#page-content').addClass(homeClass);
$('#page-content').html(hashHome);
}
}else{
//go to some page
if($('#page-content').hasClass(homeClass))
$('#page-content').removeClass(homeClass);
initAction(url);
}
})
$(window).trigger( 'hashchange' );
When the site loads its homepage, the homepage gets stored in hashHome. If user navigates away, the initAction(id) replaces the entire $('#page-content')'s content with other pages' content. When the uses navigates back to home, it restores the stored home back to the $('#page-content').
My problem is that all of the jQuery stopped working on the homepage.
I've read about live() already but it seems that it needs a event like click() for it to work. How do I fix this?
I figured out that i need to store my entire page before i change the content of the div that is surrounding it
var content$('#page-content').html();
then do the content change
that way, when i reinitialize all my jQuery plugins, they will loose all of their old reference and use the new content variable, instead of a double initialization
and finally, i've the original question's code also won't work since the script tag look like this: <script type="text/javascript">...</script>, IE for some reasons won't recognize this, so I have to change it to <script></script> in order to make it cross browser compatible

How does Rdio.com do their anchor based hyperlinks?

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();
});

Categories

Resources