Read #hash from URL with jQuery - javascript

How can I return the hash value of website.com/#something (something) from the URL with jQuery?

window.location.hash
its that simple.
donot use all those methods which consume CPU and effects performance.
If DOM provides something predefined use it first.
To pass value to PHP please do and ajax call to php.
var hash = window.location.hash;
$.ajax({
url: 'someurl.php',
data: {hash: hash},
success: function(){}
})

You can use the location.hash property to grab the hash of the current page:
var hash = window.location.hash;

update
As there is a built in method to get the hash via DOM above answer is not appropriate
var hashTag = window.location.hash
alert(hashTag);
will do the magic.
Old answer
You can do something as below if you have multiple hashes in your url
//var href = location.href; // get the url in real worl scenario
var href = "www.bla.com#myhashtag"; // example url
var split = href.split("#"); // split the string; usually there'll be only one # in an url so there'll be only two parts after the splitting
var afterSplit = "Error parsing url";
if(split[1] != null){
afterSplit = split[1];
}
// If everything went well shows split[1], if not then de default error message is shown
alert(afterSplit);
Here is an example Live Fiddle

You could use this
h=new URL(location).hash.split`&`.find(e=>/hash_name/.test(e)).split`=`[1]

Related

Why Blogger URL Related Post Undefined

I create a function using Javascript for related post on my Blogger template,
Here is my code:
function toHttps(link) {
var protocol=link.replace(/\:/g,'');
if(protocol=='http') {
var url=link.replace('http','https');
return link.replace(url);
}
}
if my original url is
https://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html
Why is the result like this?
https://dpawoncatering.blogspot.com/2008/08/undefined?
Naren Murali's answer is correct. I'd just like to add a different way of doing "protocol" swap using javascript's own URL parser that might be interesting for other people.
You can instantiate an a element and use its href attribute to parse your URL, then you can access and change the protocol attribute of the href and retrieve the resulting URL:
function toHttps(link) {
var url = document.createElement('a');
url.href = link;
url.protocol = 'https';
return url.href;
}
Since the URL contains https already it does not enter the if condition, hence nothing is returned hence we get undefined, please check my corrected function. Let me know if you have any issues!
function toHttps(link) {
if(link.indexOf('http://') > -1){
var url=link.replace('http','https');
return url;
}
return link
}
console.log(toHttps('http://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html'))
console.log(toHttps('https://dpawoncatering.blogspot.com/2008/08/nasi-box-murah.html'))

Jquery use a variable for a load query

I have a variable but I can't use it the way I want, please help!!
var test = window.location.hash;
$('div').load("test.php?id="+test);
The request keeps on being :
XHR finished loading: "http://localhost/test-site/test.php?id=".
and ignores my variable...
window.location.hash will begin with a # symbol, if it contains anything at all. You should strip it by adding .substr(1):
var test = window.location.hash.substr(1);
$('div').load("test.php?id="+test);
As it is, you are trying to load a url like test.php?id=#22, and since the hash is meaningless for AJAX purposes, it's being ignored by the .load method.
var test = window.location.hash.substring(1);

Change URL params or remove some part of URL with jquery

I have this URL and wanting to know how can I remove this section from it via a jQuery event.
Need to remove:
&activities_id=13&session_id=14&back=1
Original URL:
http://somedomain.com/ijob-css/index.php/search/default/index/area/act?query=&activities_id=13&session_id=14&back=1
EDIT
Sorry i think i havent included the most important section. I should change the Address BAR url not a normal string.
for example, if i have this url in the address bar - http://somedomain.com/ijob-css/index.php/ after change, address bar should contain http://somedomain.com/xxx=111, without page refreshing.
Do you mean you want the URL without the query parameter part? If then see if this helps.
var test = 'http://somedomain.com/ijob-css/index.php/search/default/index/area/act?query=&activities_id=13&session_id=14&back=1';
alert(test.substring(0, test.indexOf('?')));
If you want until first query parameter name then just seek until index of &
Update :
If you are using HTML5 then what you ask is possible. Check browser history manipulation. You can find details about this here.
I believe replaceState() is the answer for your problem. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.
Try this out
var new_url = old_url.substring(0, old_url.indexOf('&'));
Example: http://jsfiddle.net/SjrqF/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.slice( 0, url.indexOf('&') );
or:
Example: http://jsfiddle.net/SjrqF/1/
var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
url = url.split( '&' )[0];
var lastPart = 'query=';
var url = 'http://somedomain.com/ijob-css/index.php/search/default/index/area/act?query=&activities_id=13&session_id=14&back=1'.split(lastPart)[0] + lastPart;
var index = original_url.indexOf("=");
var new_url = original_url.substring(0,index+1);
See below.
var positionToSubstring = this.location.href.indexOf('&');
var newURI = this.location.href.substring(0, positionToSubstring);
use this
var test='http://somedomain.com/ijob-css/index.php/search/default/index/area/act?query=&activities_id=13&session_id=14&back=1';
test=test.split('&')[0];
console.log(test);
outputs
http://somedomain.com/ijob-css/index.php/search/default/index/area/act?query=

jQuery: How to get hotlink from url / hash?

I'm trying to obtain a hotlink from a url a user gets to via a link in an email
Everything after the ? below:
http://localhost:6547/m/intro/inbox/100003120?hotlink=8095cb20284c935d9ff32c0ed61b28f1&codekitCB=400521239.247318
I need to save that hotlink into a variable to POST to a new url, however my code isn't retrieving the hash or hotlink:
jQuery:
$(document).ready(function () {
// MOBILE HACKS
var path = window.location.pathname;
var hash = window.location.hash;
console.log('dashboard.init: path = '+path);
console.log('dashboard.init: hash = '+hash);
Console:
How would you get the hash/hotlink after the ? in the url above?
You can use window.location.search
That will return everything from the ? on, and then you can parse that as needed.
Theres probably a better answer out there, but I've always just used
window.location.href.split('?')
index [1] will be everything after the ?

What's the best way to force a hashchange?

My website uses hashchange-triggered AJAX (to make it more bookmark-friendly). The problem I am having is that when I click "submit" in a form, all the form data that is serialize()'d to be sent via $.post() gets lost. I know this because I get the "Flag 1" alert after I click submit, and various other tests (alerting, echoing, etc.) show this to be true.
Here's my current code:
$(document).ready(function() {
var data = '';
var hash = '';
newPage();
alert('Flag 1');
$(window).bind('hashchange', function() {
hash = window.location.hash;
if (hash == '') {
path = window.location.pathname;
hash = '#' + path.replace(/^\/+/, '');
}
data += '&func=' + hash;
var xhr = $.post(hash, data, function(result) {
$("maincontent").html(result);
})
.done(newPage);
});
// Initialize vars and handle new form elements
function newPage() {
data = '';
$('form').submit(function() {
data = $(this).serialize();
// Flag 2 - What do I do here?
});
}
// Load ajax content on first run of document
if ($('#maincontent').html() == '')
$(window).trigger('hashchange');
});
What I am trying to do is manually fire a hashchange event while also changing the URL. The trouble is that if I just set window.location.hash = $(this).attr('action'); then return false; where the "Flag 2" comment is, then I wind up getting unwanted trash in the URL, possibly due to the hashmark being encoded for a URL (...%23, etc).
I am wondering what the best way to set the hash is, and whether there is a simpler way to do what I am trying to do to begin with.
(I'm also open to comments suggesting alternate approaches for the style of navigation I am trying to achieve)
Well, I understand there are lots of errors doing this. But we have alternative options for this you will surely like:
jQuery History Plugin : http://plugins.jquery.com/history/ (Demo: http://4nf.org/)
History JS: https://github.com/browserstate/history.js/
But I would recommend HTML5 history.pushState if you are willing to avoid older browser support. (Demo: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
Good luck!!

Categories