AJAX content loader: it's SEO friendly, but what about bookmarks? - javascript

So I've started tackling Javascript and jQuery, and I've put together an event handler for certain link's 'click' events; it takes the href and pulls the content from the appropriate '#container' and loads it into the target container...
<script type="text/javascript">
$(function(){
$('#journeyNav li a').click(cLoad);
});
function cLoad(evt) {
var cLoadURL = $(this).attr('href');
if(!$(this).parent().hasClass('current')) {
$('#stageContentMain').stop().animate({opacity : 0},425, 'easeOutExpo', function(){
$('#stageContentMain').load(cLoadURL + " #stageContent", function() {
$('#stageContentMain').stop().animate({opacity : 1},425, 'easeOutExpo');
});
});
$(this).parent().siblings().removeClass('current');
$(this).parent().addClass('current');
return false;
}
else {
return false;
}
}
</script>
Everything works great actually--especially for my first jQuery function, and second overall Javascript attempt. I am however looking to on Javascript enabled machines (the bookmarking wouldn't be a problem otherwise,) make bookmarking and the 'addthis' social sharing widget to work with the selected content.
Anyone have any ideas or tips?

Checkout the Ben Alman's hashchange event plugin

Related

animated scrolling script prevents local anchor positions to be accessed from external links

I have a onepager site where I use scrollmagic plus all its necessary plugins/libraries (and jQuery) for different effects where animation, pinning, fading processes etc. are triggered by scroll positions.
I also use it for animated scrolling to the anchor points on the page (from the menu and from other local links) - see the according part of the script below.
The problem is that this script suppresses the default behaviour of "jumping" directly to an anchorpoint when a local link is clicked, and apparently also when the page is accessed from outside via a direct link or bookmark with an anchor appended to the URL (like http://www.example.com/index.php#part3). Altough this behaviour is desired when clicking a local link, it obviously prevents the browser from displaying the anchor position when an anchor is linked from somewhere else.
Is there any way to make the browser directly display that anchor position when a link like in the above example is clicked?
var sm_controller_1 = new ScrollMagic.Controller();
sm_controller_1.scrollTo(function(anchor_id) {
TweenMax.to(window, 2.0, {
scrollTo: {
y: anchor_id
autoKill: true
},
ease: Cubic.easeInOut
});
});
jQuery(document).on("click", "a[href^=#]", function(e) {
var id = jQuery(this).attr('href');
if(jQuery(id).length > 0) {
e.preventDefault();
sm_controller_1.scrollTo(id);
if (window.history && window.history.pushState) {
history.pushState("", document.title, id);
}
}
});
(It doesn't make sense to create a fiddle/codepen since the problem lies in calling the original URL from an external source).
Well assuming scroll magic doesnt have extra functionality that is not posted here that would get in the way of my answer you could try this:
Add a data-attribute to your links which you want to use default behavior:
<a href="example.com/index.php#part3.php" data-default="true">
Check if that data attribute exists and if it does return true in your click handler to continue with the default behavior:
var sm_controller_1 = new ScrollMagic.Controller();
sm_controller_1.scrollTo(function(anchor_id) {
TweenMax.to(window, 2.0, {
scrollTo: {
y: anchor_id
autoKill: true
},
ease: Cubic.easeInOut
});
});
jQuery(document).on("click", "a[href^=#]", function(e) {
if(e.currentTarget.dataset.default){
return true;
}
var id = jQuery(this).attr('href');
if(jQuery(id).length > 0) {
e.preventDefault();
sm_controller_1.scrollTo(id);
if (window.history && window.history.pushState) {
history.pushState("", document.title, id);
}
}
});
You can try and use this code:
jQuery(function ($) {
$(document).ready(function() {// if needed, use window.onload which fires after this event
if(window.location.hash) {
var hash = window.location.hash;
$( 'a[href=' + hash + ']' ).click();
}
});
});
It will wait till the DOM (or the page) is loaded and then simulate the user click on the nav item.
After I've read your question one more time, I am not sure anymore if you want your page loaded on the position of the element which is listed in the anchor or the scroll wasn't working when coming from an external source?
If the scroll was working but you wanted to display the page at the right place, like a jump, then I propose 2 solutions:
a) use the CSS opacity:0; on the body and after the scroll is finished, set it back to opacity:1;
b) try to jump on the proper place on the page before you load ScrollMagic

Jquery dynamic loading link changes

I have a dynamicpage.js script below:
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
What that code does is it makes a link turn from href="/staff" to href="/#/staff" for the dynamic loading but it only changes the link if the <a> tag is wrapped in a <nav> tag so
it only works if its <nav>staff</nav>
I tried to make it ("#dynamic") in the jquery/js and added id="dynamic" to the <a> tag but it did not work.
How would I make it so I can just add id="dynamic" to the <a> tag instead of wrapping <nav> around EACH link i want to use this.
I would use event delegation instead ..
It can be attached to the document to be triggered wherever the link is located in the DOM ( and because click event is not a flooding one like mosemove)
Then simply add the 'dynamic' class to those links concerned by this behaviour
$(document).on('click', function(e){
var $t = $(e.target),
$a = $t.closest('a.dynamic');
if( $a.length ){
window.location.hash = $a.attr('href');
return false;
}
});
If I understand you correctly, though I'm not sure I do...
Just adding in an ID to a link won't do what you want, because an ID by itself doesn't mean anything to a web browser. It's the web browser that's responsible for doing Stuff when a user follows a link, which by default would be to follow that link and load a page; you're modifying the link address so that the interesting stuff is actually held in a named anchor (hence the "#") then relying on a JavaScript event listener to catch the "click" event and do something novel.
http://www.w3.org/TR/html401/struct/links.html#h-12.2.1
There's no way around the need to attach this listener to every link that needs the special treatment.
By making sure you generate HTML such that the "interesting" links have a specific common named class though, you can at least use the jQuery equivalent of document.getElementsByClassName, which ought to be simpler and faster than using a CSS selector based approach as in your example code.
http://api.jquery.com/class-selector/
You will still have to iterate over this and add listeners. Is it really worth all this JavaScript, CPU overhead and browser incompatibility risks (especially on mobile) just to override the behaviour of a link that browsers already deal with pretty adequately? All that history patching you have to do as well (whether or not it's hidden by a framework)? Just to avoid a page refresh? Personally, I'm really not sure it is!

How to get Anchor Links to work in Jquery Mobile?

Jquery Mobile has decided to treat anchor links as page requests of sort. However, this isn't good if you have a load of blog posts which have anchor links to the same page (ie href="#specs").
Is there a way to disable jquery mobile's anchor link usage on a specific page which I know I won't be using it on so I can use anchor links as they were intended, to drop down to a part of the page?
I only need a solution for anchor links on the same page (ie: href="#specs").
thanks
You could try adding a data-ajax="false" on the anchor tag.
Linking without Ajax
Links that point to other domains or that have rel="external",
data-ajax="false" or target attributes will not be loaded with Ajax.
Instead, these links will cause a full page refresh with no animated
transition. Both attributes (rel="external" and data-ajax="false")
have the same effect, but a different semantic meaning: rel="external"
should be used when linking to another site or domain, while
data-ajax="false" is useful for simply opting a page within your
domain from being loaded via Ajax. Because of security restrictions,
the framework always opts links to external domains out of the Ajax
behavior.
Reference - http://jquerymobile.com/demos/1.0.1/docs/pages/page-links.html
If you are like me, converting an existing site and you don't want to go through every page right now. You can add one line of code to your header and all of your header and all of your existing internal anchor links will get the data-ajax="false" tag added.
Of course, this assumes you are including your own javascript file up in the header already. If you are not you would have to touch every page anyway. But I have a single javascript file that is included in every page already so I added this line...
$("a").each(function () { if(this.href.indexOf("#")>=0) $(this).attr("data-ajax",false); });
This goes in your $(document).ready() block. If you don't have that block yet, here is the entire block.
$(document).ready(function() {
$("a").each(function () { if(this.href.indexOf("#")>=0) $(this).attr("data-ajax",false); });
});
Hope this helps. It is the same solution user700284 offers but in an automated way.
You can add the following code to the end of your page:
<script type="text/javascript">
$('a.native-anchor').bind('click', function(ev) {
var target = $( $(this).attr('href') ).get(0).offsetTop;
$.mobile.silentScroll(target);
return false;
});
</script>
And add the class "native-anchor" to your anchor links.
It is not a total sollution, because the back button of your browser will move you to the previous page and not to the position of the link, but it is better than the links not working at all.
I found this sollution here: jQuery Mobile Anchor Linking
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});
First you have to place this code into a custom.js file
$(document).bind('mobileinit', function () {
$.mobile.loader.prototype.options.disabled = true;
$.mobile.ajaxEnabled = false;
$.mobile.linkBindingEnabled = false;
$.mobile.loadingMessage = false;
});
Then add this file into your webpage before the jquery mobile js is loaded. becuase 'mobilinit' event is triggered immediately
Thank you
this solution worked for me
<script>
$(document).ready(function() {
$("a").each(function() {
if (this.href.indexOf("index.php") >= 0) $(this).attr("data-ajax", false);
});
});
</script>
I replaced # with index.php which is my document root.
But, it doesn't work for form button i.e input type="submit"
// On page load on mobiles only, look for the specific a tag you want to take control over,
// alternatively you can still target all 'a' tags
$('a[href*="#component"]').each(function () {
// then set data-ajax to false,
$(this).attr("data-ajax", false);
// at this point you can add the class to your target a tags.
// You can do it elsewhere but because for this example my
// 'a' tags are automatically generated so I just add the class here
$(this).addClass('in-pagelink');
// then target the class and bind to a click event
$('a.in-pagelink').bind('click', function (ev) {
// here I redirect the page with window.location.assign
// as opposed to window.location.href. I find that it works better
window.location.assign(this.href);
// then I close my navigation menu
closeAll();
});
});

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

simulating a click on a <a>-element in javascript

for a website, i am using the jQuery supzersized gallery script: http://buildinternet.com/project/supersized/slideshow/3.2/demo.html
As you can see in the demo, in the bottom right corner there is an little arrow button that toggles a thumbnail bar. There is no option in the config files to automatically blend this in when opening the site.
So i guess i have to simulate a click on that button (the button is the tray-button, see HTML). I tried something like this:
<script>
$(function() {
$('#tray-button').click();
});
</script>
However, this doesnt seem to work in any browsers i tested.
Any idea?
$('#tray-arrow').click(function() {
// prepare an action here, maybe say goodbye.
//
// if #tray-arrow is button or link <a href=...>
// you can allow or disallow going to the link:
// return true; // accept action
// return false; // disallow
});
$('#tray-arrow').trigger('click'); // this is a simulation of click
Try this
$("#tray-arrow").live("click", function () {
// do something
});
I assume that you want to popup the thumbnail bar #thump-tray on page load.
Here's a way to do it:
locate the file supersized.shutter.js and find this code:
// Thumbnail Tray Toggle
$(vars.tray_button).toggle(function(){
$(vars.thumb_tray).stop().animate({bottom : 0, avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-down.png");
return false;
}, function() {
$(vars.thumb_tray).stop().animate({bottom : -$(vars.thumb_tray).height(), avoidTransforms : true}, 300 );
if ($(vars.tray_arrow).attr('src')) $(vars.tray_arrow).attr("src", vars.image_path + "button-tray-up.png");
return false;
});
After it, add:
$(vars.tray_button).click();
Dont forget in your page (demo.html in the plugin), to change
<script type="text/javascript" src="theme/supersized.shutter.min.js"></script>
to
<script type="text/javascript" src="theme/supersized.shutter.js"></script>
instead of using
$(function(){
//jquery magic magic
});
you culd try this witch will work your jquery magic after the full page is loaded (images etc)
$(window).load(function () {
// jquery magic
});
and to simulate a click you culd use // shuld be the same as $('#tray-arrow').click();
$('#tray-arrow').trigger('click',function(){ })
example:
$(window).load(function () {
$('#tray-arrow').trigger('click',function(){
alert('just been clicked!');
})
});
try
<script>
$(function() {
$('#tray-arrow').click();
});
</script>
Make sure that this code is after your carousel is initialized.
This looks like it's a problem of timing the trigger. The plugin also loads on document load, so maybe when you try to bind the event listener the element is not created yet.
Maybe you need to add the listener in something like the theme._init function
http://buildinternet.com/project/supersized/docs.html#theme-init
or somewhere similar.
A problem might be that your plugin detects whether the click has been initiated by a user (real mouse click), or through code (by using $('#id').click() method). If so, it's natural that you can't get any result from clicking the anchor element through code.
Check the source code of your plugin.

Categories

Resources