How does Rdio.com do their anchor based hyperlinks? - javascript

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

Related

Best Way to Load Pages w/o Reloading

I am working on building a website that will not reload to a new page every time a link is pressed. I want to make something kind of like all enterprise/popular websites. (When looking in the network dev tab: notice that youtube page doesn't completely reload when you click on a link, same with google, same with Facebook for the most part. They all usually just reload the page content and nothing else.)
I would like only the HTML between the body tags to be changed (nothing else: no js,css, no head tags, etc).
It would seem like it is pretty easy. Currently, I am just using ajax to go out and fetch the html of the page, and load that into the body. Done! Not so fast... Three things (my code is at the bottom)
The js includes are located at the bottom of the page, right before the closing body and html tags. When looking in the network tab, it shows that the same js is always gotten again and parsed again. How do I prevent that?
Some pages will not load styles that are set. (note that all css, js, etc. scripts are the same for every page)
I want to make sure that the page is completely reloaded if the user leaves the website.
I am not sure if I am looking for a fix to the way I am doing it, but probably just a completely better different way to do it.
Here is my code:
$('a').on('click', function () { //on click of any <a> tag
var where = $(this).attr('href'); //gets url of the <a> attribute
$.ajax({
type: "GET",
url: where, //where is the variable defined above
success: function(a) {
// load next page
history.pushState({urlPath: where},"",where); //changes the link of the webpage
$('body').html(a); //changes the body of the webpage
document.title = $('#title').text(); //changes the title using some weird irrelevant method
}
});
return false;
});
$(window).on('popstate', function() {//on click of the back or forward button
$.ajax({
type: "GET",
url: window.location.href, //the url is the url that the back or forward button is set to
success: function(data) {
//console.log();
$('body').html(data);//replaces data
document.title = $('#title').text();//changes title using weird irrelevant method
}
});
});

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 to reload div content on click

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

jQuery to add a class to image links without messing up when the link passes variables

OK so I was using a bit of jquery to select all the <a> tags on the page and if they link to an image file to add a zoom class to it for the purposes of a lightbox.
This is the code which works
$(document).ready(function () {
$('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').addClass('zoom');
});
There is a problem with this though;
Say I have a link which just goes to another page but passes an image url as a GET variable in the URL the lightbox is activated as a result of this and fails because the link is not actually to an image. For example:
Link text
In the above instance the jQuery script will add the zoom class to this anchor even though it doesn't actually link to a picture.
This wouldn't usually be an issue as you would leave the page to go to the link's destination before the lightbox has a chance to appear, but in times where a new tab/window is opened I get a failed lightbox coming up.
This is particularly prevalent on social media buttons such as Pinterest which passes an image url within the link.
[apologies for the title - I wasn't sure how best to phrase it. Please feel free to edit to something more suitable]
you could add the zoom class only if href attribute doesn't contain a ? (or, in other words, a querystring is not included), e.g.
$(document).ready(function () {
$('a[href*=".png"], a[href*=".gif"], a[href*=".jpg"]').each(function() {
if (this.href.indexOf('?') < 0) {
$(this).addClass('zoom');
}
});
});
You can parse the href with a simple regex to check that the image is not in the query string, and filter out the false positives.
$(document).ready(function () {
$imgLinks = $('a[href$=".png"], a[href$=".gif"], a[href$=".jpg"]');
$imgLinks.filter(function() {
return !$(this)
.attr('href')
.match(/^http\:\/\/.*\?.*http\:\/\/.*\.(png|gif|jpg)$/);
})
.addClass('zoom');
});

Link in one div, trying to load content in a seperate div

I am using jQuery to make a website, and I want to be able to have my navigation in a separate div from my content. Also, I want to be able to have a sort of tabbed navigation system such that I can click a link in the navigation and it will load the content into the main content div. Basically, I want to do this so that I can just maintain one page with all the content, rather than a bunch of pages for each section. I have included a picture that will hopefully make my question much more clear (right click and "viw image", it's too small on this page):
example http://img402.imageshack.us/img402/1733/examplew.jpg
$('#navlink').click(function() {
$("#maindiv").load("/url.html");
return false;
});
I would encourage you to use event delegation. For instance we can use the .on method to attach a single event to the navigation pane that will listen for clicks on links:
$("#navigation").on("click", "a", function(e){
e.preventDefault();
$("#content").load( $(this).prop("href") );
});
Which works with the following markup:
<div id="navigation">
Home
Gallery
</div>
<div id="content"><!-- content will load here --></div>
Considering that you want one page with all of the content, you could simple hide all but one main div with css, and then use javascript/jQuery to show one div when a tab is clicked, and hide all of the other (main divs).
Have your navigation links change the html of your center div
<a href="#" onclick="$('#centerDiv').html('your content');">Click me<a>
if you want it to be more dynamic use ajax to load it.
and if you want to get a bit more fancy try out the Tab widget
This calls for the jQuery load() function! Go to http://remysharp.com/jquery-api/ and search for 'load' -- you just need to target the div.
By the way, this is sort of an alternative to frames or server-side includes. The only bad thing about this approach is that Search Engines won't be able to follow your links.
Using ajax with jQuery its pretty simple and totally controllable:
$('#navlink').click(function() {
$.ajax({
type: "GET",
url: 'URL_OF_THE_RESOURCE',
//(maybe you can hold this in the href attr of the anchor tag)
//in that case you can use $(this).attr('href');
dataType: "text/html", //spectating HTML back from the server
timeout: 8000, //Wait 8 second for the response
error: function() {
alert('ERROR');//case of server error or timeout give a feedback to the user
}, //end error
success: function(html) {
$('#mainDiv').html(html); //Replace the content with the new HTML
} //end succes
}); //end ajax
return false;
}); //end click
Instead of usign an ID, you could use a dummy class (like "navlink") on all those navlinks, so instead of referencing the selector to the ID, reference it to the class like:
$('.navlink').click(function(){
...
and the url parameter will be:
url: $(this).attr('href'),
That way you just set this once and all the links will get the functionality and still give support to users that don't have JS active.

Categories

Resources