Use anchors/hashbangs in the URL to trigger functions on load? - javascript

Say someone is linked to the url, example.com/#boom
Can the hashbang in the url, #boom be linked to triggering a function like boom() on the page?
Thanks!

I think you want to do something like this:
window.onload = function(){
var hash = location.hash.substr(1);
if(typeof window[hash] == "function")
window[hash]();
};
If the function specified in the hash exists, then it will be called on page load.

Not sure to understand what you really want... On your web page, you can add code that runs at page load, that examines the URL and that calls a suitable function accordingly. You will want to use window.location for this.

Easily done with JavaScript:
if( window.location.hash ){
var currentHash = window.location.hash;
alert( "Yup! " + currentHash + " is set." );
}else{
alert( "Nope!" );
}
Now this is an example. Obviously you would want to call your call back function instead of outputting currentHash.
For more information on calling the function: http://w3future.com/html/stories/callbacks.xml

Maybe something like this:
window.onload = function(){ // Page onload
if(location.hash == "#boom"){ // Hash is "boom"
boom(); // call function boom()
}
}

Related

Execute a function after changing location.href

I want to call a function after redirecting the page.
Inside my function I put a parameter which is an ID but when I check the console it wont display. I know I can be able to run it via on click event but I wont get the ID param from the previous page.
Is there a way to get it done?
Code:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url; // new url
save(item_id); // call function after new url finish loading
});
}
function save(item_id){
console.log(item_id); // check if there's item_id exists
}
I agree with Katana's comment. Anything after your redirect statement will not run because the page itself is redirecting. One way that I would suggest to still get the item_id and get around that barrier, would be to include the item_id in the redirect url as a parameter. Then once on the new page, parse that parameter out of the url and save the item_id.
A great example from Cory Laviska's article on Parsing URLs in Javascript, shows how you can get the individual parameters from a URL.
Building onto Manish' answer:
Function on the current page:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
});
}
Function on the REDIRECTED Page (assuming you only have one parameter)
$( document ).ready(function() {
var url = $(this).data('url');
var item_id = url.queryKey['saved_item_id'];
save(item_id);
});
It may need a few tweeks because I didn't test the code, but hopefully it'll get you on the right track. :)
Hopefully this helps. If it helps and/or answers your question, please select as answer and up vote! :D Feel free to let me know if you have any questions
Try this one
The container is the section of your page where you perform an action.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
$("#container").load(url,function(){
// other stuffs and functionalities
save(item_id); // call function after new url finish loading
});
});
}
You can try something like this.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
//save(item_id); // call function after new url finish loading
});
}
/*(function save(item_id){
console.log(item_id); // check if there's item_id exists
}*/
Further more , On New redirected URL you can get item_id which was appended to URL in previous page.
Hope this may help.

How to load page only once

Below is my code but page load continuously,i want to load only once
window.onload = function () {
window.location.reload();
}
There are a few ways you could solve this, all of which require saving state across page loads. You could use cookies, localStorage, the location object itself, etc.
Here's a way that checks to see if there is a hash string 'reloaded' and, if not, adds it and reloads the page. Then, when it tries to execute again, the hash will be there and it will not reload:
if (location.hash.indexOf('reloaded') === -1) {
location.hash += 'reloaded';
location.reload();
}
$(document).ready(function(){
if(document.URL.indexOf("#")==-1){ //Check if the current URL contains '#'
url = document.URL+"#"; // use "#". Add hash to URL
location = "#";
location.reload(true); //Reload the page
}
});
Due to the if condition page will reload only once.
The other way to achieve this is :
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location.reload();
}
else
localStorage.removeItem('firstLoad');
}
})();
window.onload = function ()
{
// for getting params value
function parse(val)
{
var result = "not found";
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
});
return result;
}
if(parse("load")!="once")
{
//sending parameter so next time it won't reload..
window.location.href += "?load=once";
window.location.reload();
}
}
By nature of visiting a page, It will only load once. You could change your code to prove this fact:
window.onload = function () {
alert("Loaded");
}
But, I would suggest the vapor.js route to detecting page load, that is, omit this onload call, because the lines of code in the onload function run after the page is loaded. I think you either don't know what your goal is or you have an entirely different problem you are trying to solve in a way that does not make sense
You built a loop,
site is loading
window.onload is triggered
reload is initiaded
site is (re-)loading
window.onload is triggered
reload is initiaded
.......
.......
Important fact for you to learn is that browsers run through your code from top to bottom and when you reload your page, the whole prozess repeats.
So every Time you reload, the window.onload event-listener is registered and calls the function attached to it, as soon as the window object is fully loaded.
There is no mechanism that tells the browser to stop.
if you would like run your Javascript code once the DOM is loaded, and you are looking for an browser independent solution i would recommend jQuery and its $( document ).ready() function.
with jQuery included to your Page:
$( document ).ready(function(){
//Code inside this function runs after your document is loaded
})

Pass data from pop-up window back to javascript

I have a window.open function in javascript that calls a page. I then want to grab the data from that page and return it to the javascript function.
Can anyone help me do this?
$("#popup").click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
window.open(url, 'authWindow', "width=800,height=436");
});
If the page in the popup is in the same domain as yours, you can use window.opener to access data of the opener windows
In your current window :
var winopened;
$("#popup").click(function(e) {
var url = $(this).attr('href');
e.preventDefault();
winopened = window.open(url, 'authWindow', "width=800,height=436");
});
if(winopened) {
// call a function in the opened window :
res = winopened.functionInWindow();
}
hope it helped ...
window.open will return your window object.
var myWindow = window.open
Now you can play with myWindow.
The other posters answers are correct, in that they'll give you the window object. I'm not sure that's what you were asking for.
Here's a very simple way you can return the HTML from the page, if that's the "data" you need (otherwise disregard this answer).
This uses jQuery's AJAX $.get function to load HTML from a webpage, more at https://api.jquery.com/jQuery.get/
$.get(url, function( data ) {
alert( "Data Loaded: " + data );
});
From here, you can do whatever you like with the "data" variable that is returned - store it, parse it, show it...

How can I execute a script after calling window.location.href?

I have a script that redirects the user to another page. I want to load some content into a div on the new page after the new page has fully loaded. How can I do this. The following doesn't work.
function goToPage() {
window.location.href = 'http://www.mypage.com/info';
$('.my_class').load('my/url/path/with/content/to/load');
}
The newly loaded page http://www.mypage.com/info contains the following div:
<div class="my_class"></div>
What am I doing wrong?
Redirect to the new page, but append a hash signal to the URL.
function goToPage() {
window.location.href = 'http://www.mypage.com/info#load-stuff;
}
Then on load of the target page, evaluate the URL checking for that hash signal.
function pageLoad() {
if (window.location.hash === "#load-stuff") {
$('.my_class').load('my/url/path/with/content/to/load');
}
}
If your application is using jQuery it'd look something like:
$(function () {
if (window.location.hash === "#load-stuff") {
$('.my_class').load('my/url/path/with/content/to/load');
}
});
That's the rough idea at least.
As pointed out in the other answers, you won't be able to perform any script instructions from your original site. Instead of using PHP to create the content statically, you could also use HTML fragments as arguments, e.g. like this:
// in the original page:
function goToPage() {
window.location.href = 'http://www.mypage.com/info#my/url/path/with/content/to/load';
}
// in http://www.mypage.com/info:
$( document ).ready(function () {
if(window.location.hash)
$('.my_class').load(window.location.hash.substring(1));
}
An easy way to pass data to your page you are redirecting to would be to set some url parameters.
For example:
window.location.href - "http://youpage.com/?key=value"
When that page loads you could have a:
$(document).ready(function(){
var my_param = getUrlParameter('key');
if(my_param == "value"){
//do your stuff here
}
});
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
You should just run
$('.my_class').load('my/url/path/with/content/to/load');
on this page: http://www.mypage.com/info.
When you do window.location.href = 'http://www.mypage.com/info'; you're redirecting to another page. Nothing after that line will happen. You have to instead run the code after that line on the page that's loaded.
You can do this a few different ways. Try leveraging the localstorage API and passing info or content with a name and value pair (or a few of them) and unpack it on the receiving end.
On the page you're redirecting to, check for the localstorage key, and then load the contents of it (the aforementioned name and value pairs) into a div.
As an alternative, you can write one script file that you can deploy to several pages; do a check on window.location.href and conditionally load script accordingly. If you're on the redirected page, you can run whatever script you like. The nice part about doing it this way is that you're still working with one JS file - no need to fragment your code (assuming, of course, that the pages you're working with are all on the same site).
You don't need to do anything with php if you don't want to, or hashes... there's a few nifty tools that will do the trick if you can leverage HTML5 and its associated APIs.
window.location = '#/MyPage';
setTimeout(function() {
//MyCode To Run After PageLoad
});
You are redirecting the browser with window.location.href and I'm afraid as you are purely just changing the browser's location, you can't have any affect/input on the page you are moving to (unless you use query string parameters and then create content with something like PHP (myurl.php?newcontent=whatever) )
Once you redirect you can no longer execute scripts on that page, as the page is unloaded.
Try this,
redirect page:
function goToPage() {
window.location.href = 'http://www.mypage.com/info;
}
mypage.com/info:
js:
$('.my_class').load('my/url/path/with/content/to/load');
html:
<div class="my_class"></div>
I hope this helped you out, and let me know if you need further assistance!

How to call a js function when url contains anchor

I have a site example.com.
When I visit this page example.com/#login I want to call a js alert function.
How can I do this?
// example.com/#login
if (window.location.hash) {
alert("URL has hash");
var hash = window.location.hash; // = "#login"
callMyFunction();
}
If you want a good cross-browser library for dealing with url's, I'd look into History.js
https://github.com/browserstate/History.js/
History.Adapter.bind(window,'statechange',function(){
// Note: We are using statechange instead of popstate
var State = History.getState();
// Note: We are using History.getState() instead of event.state
History.log(State.data, State.title, State.url);
});
And there's also Backbone.js, which may be way more than you need because it's an MV* framework, however it has a concept of a Router which is also helpful.
http://backbonejs.org/#Router
You can check the URL for #login. If it's present call the function.
http://www.webmasterworld.com/forum91/216.htm
I recommend jQuery, and this approach:
http://jquery-howto.blogspot.co.uk/2009/09/get-url-parameters-values-with-jquery.html
I think you can check if window.location.hash isn't a falsy value to check if there is a hash in the URL.
For example:
function someAlert(message) {
// This would be your alert function. This is just for example
alert(message);
}
// The "if the URL has a hash":
if (window.location.hash) {
someAlert("Hello URL with a hash visitor!"); // "Hello URL with a hash visitor!" can be whatever you want
}
If you want to save the whatever is after and including the hash, just use:
var hash = window.location.hash; // hash would be "#login" if the URL was http://example.com/#login

Categories

Resources