How do I do ajax navigation on pageload? - javascript

I have a page with several reports that are produced via ajax calls. I am prototype.js framework on this page for some of the display functions.
The links for each report have anchors/tags like #Report1, #Report2 etc, which are hrefs with onClick functions that do lots of work to create the report via javascript.
I would like to make it so if a user bookmarks a page with a link or navigates directly with a anchor/link in the url for my page to load the report.
So if the user goes to : http://mysite/myPage.jsp#Report2 it should load the page and go to the 2nd report.
Is there anyway in my pageload I can look at the anchor/link and perform the onlcick for that anchor? I was thinking I could create a big case/if statement to figure out what to do, but maybe there was an easier way.

It all depends on how you're Ajax calls are structured really. I do something similar for opening the correct tab within a tab navigation. The code would start off like this, if you let me see how your Ajax events are hooked up then i should be able to show you the rest.
document.observe("dom:loaded", function() {
if(window.location.hash){
var report = window.location.hash.replace("#","");
}
});
EDIT
Looking at your code you would be much better off (imv) switching to an unobtrusive method where you attach events to your elements e.g.
$('ele').observe('click',doStuff.bindAsEventListener($('ele')));
This would enable you to more easily connect the same functionality to a click or a pageload but is also better practice anyway and would prevent code duplication etc. Obviously this is missing large chunks but hopefully you get what i mean

Related

How to stop scroll event function when the user move to another page

I am adding the scroll event in javascript for one of my pages. The code is like this:
document.getElementById("myProject").addEventListener("scroll", myFunction);
function myFunction() {
document.getElementById("scrollEvent").innerHTML = "These are all my projects so far";
}
So, when users start scrolling, they will see a text "These are all my projects so far".
My problem is how to stop showing this text when users move to another page.
Please help ( I am a verrrry fresh developer)
Thanks so much
A few thoughts.
Without knowing your dev environment (e.g. are you using MVC with a framework?), I will assume you are simply talking about separate/individual HTML pages.
Each HTML page can have its own javascript. Just like HTML and CSS, there is no need to have the same javascript functions on every page. (You don't have the same HTML content on every page, right?) Usually, we divide up the javascript into multiple files - some files are added to every page, some are specific to a certain page. It is easiest to have one (external) javascript file that you reference on every page, and then specific javascript code for each page - either in a second external file that is referenced, or on the HTML page inside <script>//js here</script> tags.
If the DIV with ID myProject is not on the other page, then the javascript won't do anything. However, it is not good to have broken javascript on a page, so make sure it is not included on other pages.
If you are using a framework, like CodeIgniter or ReactJS or Angular, please tell us so we can adjust our answers accordingly.
If the case is a switching between browser tabs, you can use two different events like below.
$(window).blur(function(e) {
// stop scroll event, when switching to another tab
document.getElementById("myProject").removeEventListener("scroll");
});
$(window).focus(function(e) {
// start scroll event
document.getElementById("myProject").addEventListener("scroll", myFunction);
});
I am not sure what you are actually looking for, because when user switch between tabs, he can not see the text anymore no matter there is a scroll event or not. If you are concern about performance, then the above solution would help.

Can I load a javascript file with a partialView in asp.net-mvc?

I have an asp.net-mvc website where there is a top section with a bunch of filter information and the middle section is a reports. I now have a few different report formats and I want to toggle between a few reports. I have it working by making them all partial views and loading them via ajax (to avoid loading the common info over and over again) but one issue i realized is that some of the different reports have different javascript that goes along with them. For now, I am loading up all of the javascript files in the main parent page but I realized that I am wasting a lot of resources by download and wiring up all of the jquery events even if i never actually view a report
Is there anyway I can pass some javascript along with downloading a partial view in asp.net-mvc so I only load this and wire up the events "on demand" as required (instead of always)
Of course you can. Just be aware that the effects of the code will stick around even if you later remove the code itself: any functions you defined will remain defined, any listeners you attached will remain attached (as long as their target elements persist)... so it would be a good idea to make a setup() and teardown() methods for the loading code, that you'd invoke from your controlling code, rather than just drop a bunch of code to execute as it loads.
However, I would say it would need to be a rather unique set of circumstances for me to employ this method; for most part, it would be much easier and efficient to just load all the code you need at once, to benefit from client caching if nothing else. Toggle the behaviour of your code, don't toggle the code.

Can I create a JavaScript that fires when any get or post method is called, including Ajax requests?

Anytime I click on a link/button anywhere on my site that performs/calls a GET or POST (Ajax and non-Ajax), if it takes more then a few seconds I would like to display a loading gif. I know how to do this on an individual basis, but I would like to know if it is possible to create a function that will do this automatically and then hide the gif when finished (assuming it does not redirect to a new page).
I found this but this does not work with the post method for spring security for example.
It may be a case where it is not possible or requires more effort than it's worth. I would just like to know if it is possible and if so how might it be approached.
The only constraint is that any methods calling the post or get should not need to be aware of this so called "listener".
This is tagged jQuery so I'm giving a jQuery answer for simplicity. This is also solvable in a relatively simple manner without it.
Hooking on every request:
Let's say your method is called myMethod.
GET/POST requests may be triggered the following ways:
Form submits, in which case you can select the form $("#formID").submit(myMethod); . Note that if myMethod returns false it will cause your form to not submit
AJAX in which case you can use $.ajaxStart with $.ajaxStart(myMethod)
"a" tag clicks, and other click handlers, in which case you can perform $("a[href]").click(myMethod) , note that this selects all a tags with an href attribute, you might want to change the selector to suit your needs
Image loads which you can handle like explained in this question.
Script loads which you can detect like explained in this question.
Stylesheet/Link loads, which is explained in this blog post. You can add a hidden element to the CSS and check if the style was applied in an interval, and when it does call myMethod
What you can't do:
If your page has a plugin like Flash, or in general anything your JavaScript does not have access to, you can't hook on requests it makes.
The case of displaying a 'loading' gif.
From what you're asking it seems like you only care about image requests, and AJAX requests (correct me if I'm wrong), since external pages that take a long time to load NOT in an AJAX requests can (should) implement that .gif logic on the new page. This could be handled as I explained above.
Although you can hook every case, I would not do so. I would create a method that loads the 'loading' gif into a place and accepts a url. If that url is an image (for example, by file extension if that's ok with your mapping) use the logic in the image load detect linked question, if it's AJAX load the loading gif to where the data will be loaded, and replace it with the data on a .done() handler.
Here is a question about how to do this for an image, here is how to do it for AJAX . The two can be easily combined into a method which is what I believe you should use.

Handle browser back button with Javascript / different approach possible by using anchors?

I'm currently struggling with a good navigation on a website using Ajax calls and unobstrusive JS. I'm catching the click event on links, load the content, attach it to a div and then return false. This works quite well and also allows Google to crawl the site with speaky URLs.
But I didn't know how to deal with the browser back button. I found this solution to catch the event when the user clicks on the back button:
http://www.bajb.net/2010/02/browser-back-button-detection/
It works quite well. But I also want the back button to work normally when the user found the website via a link and wants to return to the previous page (I don't want to trap anyone).
When I thought about it the best way would be to use anchors. The normal back button supports them and you can go back in history without reloading the page (/#1 <- /#2 <- /#3 etc.)
It would work like this:
Use normal URLs in the link, but catch the click event
When user clicks, load content and attach it to a DIV
Change the window.location, using an anchor (e.g. 'domain.com/#products/women-clothing' with window.location="#products/women-clothing";)
When the window.location changes, get the anchor, read out the path and get the content via ajax, attach it to a DIV
Only the last part isn't really clear for me and I could need help here.
Finaly, my question: Does this make any sense?
Thanks!
Just add the href to window.location.hash after loading the content into a div. Then you can use that back button detection script to load what ever is in the hash.
I solved the problem by using this great jQuery Plugin: History.js
Thanks!

Anchored AJAX and SEO workaround?

You all know how to build AJAX sites with those 300ms trigger for checking anchors (hash links) in URL and then loading proper page with AJAX. But, these anchor links are nothing to search engines =(
I've thought of making some kind of workaround. All JS code remains the same, but, this little thing (I'm with JQuery, sorry):
$('a').live("click",function(){
var lnk = $(this).attr("href");
document.location.hash = lnk;
return false;
})
And then, you replace your anchor links in the body with plain links, build corresponding plain pages (still containing all JS codes) for non-javascript users and search engines. For normal visitors you would have plain links converted into hashes on fly and AJAX content loaded immediately. For those who are trying to load certain pages found through search engine - they will, and after that visitor will continue to move around with ajax navigation... somehow (remember, those plain direct pages still contain JS code).
I just want to make sure my assumptions are right. Are they?
Update: Bad thing is that when user directly enters some internal page with for ex. /portfolio address, he would then continue to /portfolio#contacts or similar URLs that are not so pretty, but still working (I mean /portfolio#contacts would show contacts).
That doesn't seem to be a good approach mainly because you'll end up having that function being triggered for the click event of each and every link, even those where you do not want to use your AJAX approach for loading content, for instance links to other sites or to javascript:....
If you place all your AJAX-y links under the same class or use another attribute to distinguish them and then adapt the jQuery selector that you're using there, then it will work and it will be a good approach because not only will it be SEO-friendly, but it also provides graceful degradation, that is, your users will still be able to access the content even if they're running in an environment where no JavaScript is allowed.
Other than that, and if SEO is your only concern, you may search the web for what a sitemap.xml file is and how to use it. Wikipedia has an article on it that may be worth a reading.
Sounds very sound... only I would suggest the callback on your 300ms timer also be called inside the event you have above, that way you have an instant result when clicking a link(and also a user can goto the link in the address bar and get the same effect)
Hey mate, you probably want to check out jQuery Ajaxy. It gracefully upgrades websites into rich ajax applications, so your website still works for SEO and Javascript disabled users.
You can see this functionality in action in this upcoming website. Notice how all the links are the same as they would be if the website isn't a Ajax application - and they still work if you right click and go open in new window!
This functionality is explained in detail at it's demo page. You can also find other examples and usage instructions there to:
http://www.balupton.com/sandbox/jquery-ajaxy/demo/
Overall to use it is surprisingly simple and straightforward (especially considering what it allows you to do!), and the support is fantastic.

Categories

Resources