Remaining the same state of a webpage - javascript

So I've made a web app, image below. The app has several tabs which contain different information such as graphs and indicators. The app is made using HTML & Javascript and is one document. I have implemented a Javascript timer which, every 60 seconds, loads the exact same webapp but in a different HTML document, just with different values for the graphs etc. This was just to make it easy for me as i don't have a lot of time at the moment. So every minute the web apps graphs will refresh with different data coming from a different document. So basically i have index.html, index2.html and index3.html, all with the same code/webapp but loading different values into the graphs. Heres the code for the timer:
<script type="text/javascript">
var myVar=setInterval(function(){myTimer()},60000);
$(function () {
});
function myTimer()
{
window.location.replace("index2.html");
}
</script>
The only problem with this is that when, for example, index.html reaches 60 seconds and loads index2.html it goes back to the very first tab (Summary), is there anyway to remain on the same tab even though it's loading a different document?

As #JoshuaM pointed out, the best solution would be to use AJAX, but since you seem mostly satisfied with your current method, you could use a hash on the URL to indicate which tab should be active, e.g.:
index.html#/metrics
index2.html#/metrics
etc...
(I like to put in a leading slash for this sort of thing to distinguish it from a regular anchor link or unexpectedly jumping to an element with the same ID, but in a simple case like this, index.html#metrics could work just as well).
The link for the metrics tab would look like this:
Metrics
(Keep whatever Javascript you have set up on it to make the tabs work.)
Then, when loading the next page, append the hash to it:
var nextPage = 'index2.html';
window.location = nextPage + window.location.hash;
Finally, check for the hash when first loading a page:
var hash = window.location.hash;
//hashes indicating which tab to make active should begin with a slash, e.g. #/metrics
if (hash[1]=='/') {
var currentTab = hash.substr(2);
//activate current tab...
}
Another alternative would be to use an iframe for the graph content but that would probably require more reworking of your code.

Related

Detect which link was clicked with javascript that got user to specific page

Been searching on the web for a solution, but couldn't find anything, so maybe it's not possible, although I hope it still is.
What Im trying to do is detect the button (class or id) that was clicked when being redirected to another page on my site.
What I have is a portfolio page that contains a large amount of divs with different classes, so when someone clicks on a specific button on the homepage and gets redirected to the portfolio page, is it possible to detect on the portfolio page how the visitor got directed from. So detect which button got clicked.
no idea how to approach this, something maybe with if previous window.location last action find class or id.
Hopefully my question makes sense and someone can give me an idea if even possible.
I imagine it would rather be possible to do with php, but unfortunately server side languages are not an option in this case.
Thanks
Examples of methods you can use
add the information in the originating url - use location.search or location.hash depending on your choice of ? or #
Set a cookie (or use session/localStorage in modern browsers) in originating page and read it in the target page
Interrogate document.referrer (not always set)
You can't do it without either modifying the links (adding a query string or hash), or having code on the source pages (where the links are).
The former is pretty obvious: Just add a query string or hash (I'd use a hash) that identifies where the click came from, and look for the hash on the portfolio page. E.g., links:
Portfolio
Portfolio
and in the portfolio page:
var from = location.hash;
If you don't want to do that, and you can put code on those pages, it's easy: Add a click handler that sets information about the link in sessionStorage (very well-supported on modern browsers), and look for it in sessionStorage when you get to the portfolio page.
E.g.,:
$(document).on("click", "a", function(e) {
// Maybe check the link is going to portfolio, or refine the selector above
sessionStorage.setItem("linkFrom", this.className);
});
and then in the portfolio page:
var from = sessionstorage.getItem("linkFrom");
You can use window.localStorage to save the last id of the clicked element.
localStorage.setItem('last_clicked_id', id);
And then read it in the next page:
localStorage.last_clicked_id
Before running you should check for localStorage support:
if(typeof(Storage) !== "undefined") {
//localStorage code
} else {
//no localStorage support
}
this is how it works: the recent page or url is set on the URL parameters like a GET server request, but instead the client will receive it and parse it not the server. the recent page or url is on the "fromurl" parameter. on every page put this in (it's a javascript code):
function getURIparams(s) {
loc = window.location.href;
loc = loc.substring((loc.indexOf("?")+1));
loc = loc.split("&");
for (l = 0; l < loc.length; l++) {
lcc = loc[l].split("=");
if (lcc[0] == s) {
return lcc[1];
break;
}
}
}
next on every anchor link put this in href:
The Link to another page
after that, on every page execute this javascript:
from_url = getURIparams("fromurl");
the "from_url" variable will be the string variable of where the user clicked before it comes to that page.
if you are to lazy to put all those anchor one by one like this, do this work around but you need jquery for this. you dont need to put the parameter on the links for it to know where it comes from it will be automatically added by jquery.
$(document).on('click', 'a', function(e){
e.preventDefault();
window.location.href = e.target.href + "?fromurl=" + window.location.pathname;
});

How to navigate to a dynamic appearing url in javascript

I am trying to make a small JavaScript code meant to be put in a bookmark on Google Chrome (So that it can easily be used on the console).
1) It is intended to look at a specific forum-type website I use where new posts appear dynamically on the page at a managably slow rate (1 every 5 or so minutes usually). I mainly want the script to check the page every few seconds for new posts that I haven't visited yet, and then navigate to a single unvisited post.
2) On the post's page I want it to click or otherwise activate an html button (each page will have the same button with an example id="enbut")
3) And afterwards go back to the main (static) page and wait for another post.
I am rather new to JavaScript, and I have a basic knowledge of html, but this type of thing is beyond me. (Sorry if my formatting is horrible, I'm still figuring it out)
I have come as far as:
javascript:
setInterval(function(){
window.location.href = 'http://theforum.com/new-posts';
document.getElementById('enbut').click()
}, 60000);
My main issue is recognizing and navigating to a single post on the page that I haven't visited yet, if anyone has a method to recognize unclicked/unvisited links and then navigate to them that would be the answer.
EDIT:
I have found a way to change the color of unvisited links to cyan using this code:
function addGlobalStyle(css) {
try {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
} catch (e) {
if (!document.styleSheets.length) {
document.createStyleSheet();
}
document.styleSheets[0].cssText += css;
}}
addGlobalStyle('a:visited { color: #837768 } a:link {color: #00adeb');
So now I need to find a way to navigate (in the same tab) to a link in the color #00ADEB. I am also worried with how it will decide which link to go to, since there will inevitably be situations where there is more than one unvisited link on the page.

Add to favorites button for adding favorite html Pages

I am creating a mobile website with different events in a specific month. I want to add a button on every event page let user add different as'favorites'. I want that when user click the Add to favorites button, the event should be automatically added to a html page 'favorites'
I would go with a small javascript, external and called on the event pages (since there will be many instances of it). It's actually a very simple process you're asking about.
Create a new javascript file called favorites.js
Save it with this code:
Modified To support Opera
function bookmark(title,url){
var sPath = window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
url =url+sPage;
if (window.sidebar) // firefox
window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
var elem = document.createElement('a');
elem.setAttribute('href',url);
elem.setAttribute('title',title);
elem.setAttribute('rel','sidebar');
elem.click();
}
else if(document.all)// ie
window.external.AddFavorite(url, title);
}
In the head of every HTML document you write, you need to call this script (extremely similar to calling a CSS definition):
<script src="**/dir/**favorites.js" charset="UTF-8" type="text/javascript" defer/></script>
Defer is optional but recommended with a script like this which is not essential to the functioning of the page. However, if you want the possibility that the user can make use of the add to bookmarks function before the rest of the page loads, you may change defer to async.
Now you're almost there. At this point, to save yourself some frustration, make sure that your pages load without error before trying to use a link. This will ensure there are no bugs with your javascript or existing code.
To make use of the add to favorites button, it's as simple as using anchors and links. A link which would make use of this script in particular looks like this:
bookmark me
or
<img src="imgs/bookmarklogo.png" **other-img-definition-stuff**>
And in the old days it was common to use a form button, like this:
<input type="button" name="Bookmark this page" onclick="bookmark()" />
Several years have gone by since I really bothered myself with HTML/CSS, and in that time, options such as AddThis have come about. If you find this task too difficult, I would just go with something like that. And also I would recommend getting away from handcoding and go to some sort of CMS, like Drupal or Wordpress. Especially if you are on tight schedules.

What to do if $(window).load(function(){}); is too early

I need to trigger a piece of code after every single bits are done downloading. The script works if injected after everything is loaded, but how do I trigger that automaticly?
My script is:
var divId = "jwplayer-0_wrapper";
if ($('#' + divId).length == 1) {
myReg = /https?:\/\/www\.youtube\.com\/watch\?v=[^"]+/;
var plainText = $('#' + divId).parent().children('script').text();
var url = plainText.match(myReg);
if (url !== null) {
window.location = url;
};
};
It is used to skip certain site that decide to use the JW player witch I find horribly buggy. So it looks for a div with the indication of the JW player and if there's one, it finds the link to the original youtube video and directly goes there.
Its triggered By Google Chrome Add-on named Javascript Injector and I apply the script on every page I visit. The plug in work perfectly well on sites like www.ayoye.co and www.veuxturire.com. But on other sites, that uses the same pathern, it seems that the script is triggerd too early. For example there www.mondedestars.com and www.lesautos.ca triggers it too early.
If I use the "inject now" fonction of the Add on after the page is really done loading, then it redirects me to the youtube page as expected. I am lost on the why it works some where and not were else.
I'm not trying to understand every single website here, I'd prefer make it dynamicly triggered after the page has done loading everything from its php, ajax, script, flash, html and CSS.
I've tryed to look to the JWplayer API, but since its terribly unclear to me, over the fact that its partialy in flash, it woudl be simpler if there was a way to trigger it after, or maybe just triggering it after i hover over the body, since every sites has a body. It cant be specific to one page.
Use something like this
var timer;
function injectYouTube() {
// DO YOUR STUFF HERE
// ONCE DONE CALL clearInterval(timer);
clearInterval(timer);
}
timer = setInterval(injectYouTube, 2000);
I am not saying this will be called after everything is loaded but instead you can make sure your code is executed when you want it to.
The JWPlayer API are not that difficult. You can retrive the informations you need even not knowing the container id.
This is an example:
var player = jwplayer(0); // get the first jwplayer element of the page
var video = player.getPlaylistItem(); // get the player video
var url = video.file // retrieve the video url
I think the setTimeout or setInterval are unreliable.
Setting up a listener on jwplayer onReady event would be better.
The pessimistic answer to this is that you can't wait until a page has finished all AJAX operations etc. because web pages can continue loading new content indefinitely if they wish.
What you might consider is running your code every time a new HTML element is added to the page. This way, you can be certain to catch JWPlayer the moment it is inserted into the page.
document.addEventListener("DOMNodeInserted", yourRemovalFunction);

passing different variables to same page

I am trying to build a web app mainly using html and javascript. I use a number of different variables in the app that are passed through the url.
here are the problems, I have some links that link to the page the app is currently on, just with changed variables, but while clicking on the links does change the url value, the page does not change/reload for the new values when using and an href, is there a clean way to force the page to reload if you link to the current page, or change the url?
currently I am using jQuery to set the window.location with the new variables then reloading the page.
also, I have a similar problem for using the back button on the browser. It will change the url but not refresh the page, so if you have a variable set to 1 you change it to be 2, that works and the page will reload with the variable set o 2, but if you go back using the browser history the url will say that your variable should be 1, but the rest of the page will still act like the variable is 2, until you refresh the page.
is there someway to set a page so that the it will automatically refresh when you go to the page from the same page, either through links or going forward or backward with the browser history?
as per request here is part of the parts of the code I am having problems with:
first is the code for the creating the html elements onload
var sel_tags=document.getElementsByName("selected_tags")[0];
var temp="";
if(Tags==null)
{
temp="\<p>All Notes\<\/p>";
}
else//Tags not empty, and there are tag filters
{
var click= new Array("",a+ AtTagShow);
var GoTo="PageViewNotes.html?"
for (var i=0; i < Tags.length; i++) {
//if we are showing #tags, or a tag is not an #tag
if(AtTagShow||Tags[i][0]!="#")
{
click[0]=t+Tags[i];
if (temp.length>0)
{temp+="\<span class=\"spacer\">\/<\/span>"};
temp+="\<a class=\"selected_tags_label\""+
"href=\""+GoTo+click.join("&")+"\">\<span>"
+Tags[i]+"\<\/span>\<\/a>"
}
};
};
sel_tags.innerHTML=temp;
here is the jquery code for setting the onclick:
$(".selected_tags_label").live("click",function(){
window.location=(this.href);
window.location.reload();
});
an example url for this issue would be:
page.html?Tags=#rediculous,#meeting&AtTagShow=true
by clicking on the rediculous element the url would change to:
page.html?Tags=#rediculous&AtTagShow=true
window.location.href="page.html?Tags=#rediculous&AtTagShow=true"
Take a look at the jQuery History plug-in for setting your site up to have back / forward history. It helps with setting up states on your page, that call data based on what query parameters are in the URL string.
In modern browsers (IE8+, Opera 10.6+, Fx 3.6+, Safari 5+) you have hashchange event.
Instead of reloading page, maybe you can achieve desired results with something like this:
<script>
document.onhashchange = function(){
// do something
}
</script>
MDN might be also helpful.
If you are using query parameters (things after the ? mark in the URL), then changing a query parameter and setting window.location to that new URL should cause a new page load from the server.
If you are using hash values (things after the # mark int he URL), then changing the hash value will not cause a new page load.
So, if you want a fresh page load from server each time you change a value, then you should be using query parameters. Back and forward should also work fine when using query parameters.
If you're purposely trying to do all of this with hash values to avoid an actual server page reload, then you will have to do more coding to intercept hash changes and process them. That is easier to do in modern browsers than older browsers using the window.onhashchange event. See this page on MDN for more info.
Browser reloads the page, whenever any of these parts of the URL are updated via window.location:
Domain
Port
Path
Query string
But it won't load the current document, if you change the fragment_id part (which is simply a reference to an HTML element inside the current document).
Thus from what you say, I guess you're updating the fragment id.
Also this might help to know that window.location.reload() method does the work of F5 key.

Categories

Resources