taking the # out of url on location.hash - javascript

function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.

Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)

You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}

If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.

Related

Change current URL then load

I want jquery to find and change the current URL you are visiting and load the new one. Lets say jquery is supposed to change the current "index.html" to "indexalt.html" on click and then load it. My idea is to use document.URL to get the current URL then slice off ".html" at the end and add for example "alt.html" to string. I'm very new to jquery and don't get it to work. There will be a lot of mistakes within my script probably:
$("#contact").on('click', function() {
var url=document.URL(str.slice(-7));
.load("url +"alt.html"");
I would really appreciate if anyone can tell me how to do it and how to write it down correctly in a whole. Thanks!
location.href returns the URL of the page. So, you can do this instead.
$("#contact").on("click", function() {
// Slicing 5 characters from the URL.
const url = location.href.slice(0, -5)
// Simply load the URL
location.href = url + "alt.html"
})

Redirect in Javascript with multiple query params

I have this code :
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val());
window.location = "http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val();
}
In the console I have
http://myWebsite.dev/dailyGift?id_event=41?week_id=44?year_id=2016.
When I access directly works without problems, but jQuery does not make this redirect and I don't understand where is the problem.
You need to change all the ? with & except the first one
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'&week_id='+$('#week_id').val()+'&year_id='+$('#year_id').val());
}
Please replace all "?" with "&", Correct URL would be :-
http://myWebsite.dev/dailyGift?id_event=41&week_id=44&year_id=2016
Also it would be good if you encrypt ids for security purpose.
You say that you want to redirect to a link but you're merely changing the location.href value which is equivalent to clicking a link.
Location.replace() will load the new resource in place of the current one. The current page will not be added to the session history so it will not be possible to return to it using the back button.
I've also cleaned up the use of " and ' in the url string to make it cleaner.
if ($('#category').val() == 4){
var url = "http://"+window.location.hostname+"/dailyGift?id_event="+$('#sub-category').val()+"&week_id="+$('#week_id').val()+"&year_id="+$('#year_id').val();
console.log(url);
window.location.replace(url);
}

How to get previous url including hash fragment using JavaScript?

I need to get the previous url to redirect to the previous page. I have url like www.mysite.com/users/register/#1.
I use document.referrer to get the previous url,but it doesn't return hash part(#1). How to get the previous url including hash part?
How to get previous url including hash fragment using JavaScript?
As you've noted, the hash fragment part of that means you can't use document.referrer.
If the previous page was on the same origin: You'd need to have code on that page recording the full URL, for instance in sessionStorage.
On the previous page, perhaps each time hashChange is fired:
sessionStorage.setItem("last-url", location);
On the new page, to get the URL:
var lastUrl = sessionStorage.getItem("last-url");
If the previous page was on a different origin: I'm fairly certain you can't.
I need to get the previous url to redirect to the previous page.
Actually, you don't. You can just use history.go(-1) or history.back() to do that, which work regardless of the origin of the previous page.
try for previous url,
function backtopage() {
window.history.back();
}
May be you can use onhashchange event.
When url is changed,it produces a event with old url and new url.
The oldurl has even the hash part
$(window).bind('statechange',function(){
// Prepare Variables
var State = History.getState(),
url = State.url,
states = History.savedStates,
prevUrlIndex = states.length - 2,
prevUrl = states[prevUrlIndex].hash;
});
Try this one::
In previous page url:
www.mysite.com/users/register/#1
In Current Page:
$(document).ready(function() {
var referrerUrl = document.referrer.replace("#","e");
var correctUrl=referrerUrl.replace("e","#");
});

Remove parameter from url not working

I'm attempting to remove a url parameter status from the url but in the following alert, the parameter is still there.
var addressurl = location.href.replace(separator + "status=([^&]$|[^&]*)/i", "");
alert(addressurl);
location.href= addressurl;
How do i solve?
You are confusing regex with strings.
It should be:
var addressurl = location.href.replace(separator, '').replace(/status=([^&]$|[^&]*)/i", "");
Javascript context in web pages are to the page you are working on.
When you reload, redirect or move to any other page, javascript changes done in previous page will not be there. This has to be handled from server side.
Refresh repeats the last request to the server, which is going to ignore your javascript changes. Instead navigate to the new url with window.location = addressurl;

Ajax Loading of Page Without changing the loaded content after refresh

The situation is that I have links:
Edit Account Info - that points to http://example.com/user/edit
I setup a javascript that will only fetch information in the controller then will load it in a template.
I have this code that does the eventhandling
$("#lnkEditUser").on("click",
function()
{
some.settings.edit_profile();
return false;
})
What it does, is that it replaces the content of a div with the template,
so I have it loaded, the template and the details from the controller(from the model) via ajax calls. The problem is that when I try to refresh the page, the content would be its default. Is it possible that when I click on the link the URL will then change to something like:
http://example.com/user#edit
So even when I refresh the page, the content loaded via ajax will be the same?
If I remove the #edit, it'll be the default?
Correct me if i did this right, or if there is a better way to do it..
first I check if the hash exist, then get the value of the hash, assigned it to variable hash then i removed the hash, maybe i can do also do this replace("#", ""). I realize other stuffs while i'm typing this like i should have been converted it hash to string right on the assigning of value. But anyhow, this is how I did it.
activeTemplateViaHash : function() {
if (window.location.hash) {
var hash = window.location.hash;
hash = hash.toString().substr(1, hash.toString().length-1);
var method = new Function('some.settings.' + hash + '()');
method();
}
},
Try doing this:
activeTemplateViaHash : function() {
if (window.location.hash) {
var hash = window.location.hash;
hash = hash.replace("#", "");
var method = some.settings[hash]; //find the hash method
if(method) { //if the method exists then run it
method();
}
else {
alert(hash + " function doesn't exist!");
}
}
},
But instead of relying on hashes like that, I would use localStorage or COOKIES to store user settings easily.

Categories