I'm trying use the jQuery to change the url query string without reload the page, the link may be like this www.example.com/innerpage?tab=xyz¶=abc .. I want to append these queries when click on a links inside that innerpage. So when copy the link and share with other I'll read these queries to open the targeted section again!
function getParameterByName(name) {
url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$('.alink').click(function(e){
e.preventDefault();
var _link = $(this);
var _target = _link.attr('href').substr('1');
var target = $('div[id="'+_target+'"]');
$('html, body').animate({
scrollTop: target.offset().top
}, 500);
var urlq = getParameterByName('tab');
if(urlq != null){
location.href.replace("tab="+urlq, "tab="+_target);
} else {
location.href+= "?tab="+_target;
}
console.log(urlq);
});
check out my code on my codepen