Reputation: 629
I have a function that adds items in my URL without page reloading. I use this in a filter function. Every time some one clicks an item in the filter, this function will add the clicked item in the URL. If you click the same item again, the item will disappear again.
function childboxes(MainElement, ChildElement){
var pathArray = window.location.pathname.split( '/' );
var extra = pathArray[2];
var clicked = "&"+MainElement+'='+ChildElement;
var re = new RegExp(clicked, 'g');
if(extra.match(re)){
//remove item from URL
var extra = extra.replace(clicked, "");
window.history.replaceState(null, null, extra);
}else{
//Add items in URL
window.history.pushState(null, null, extra+"&"+MainElement+'='+ChildElement);
}
}
Example: http://www.domain.com/en/webshop&brand=18&category=shoes&product=test
And there is my problem, every added item adds this: &brand=18 As we all know, the first parameter has to start with an "?" instead of an "&".
I have no idea how to make sure the first item begins with an question mark.
Using something else then pushState
and replaceState
is fine by me. The only thing I want is that the page isn't reloading when we update the URL.
Upvotes: 1
Views: 1783
Reputation: 2495
Just simple check:
window.history.pushState(null, null, extra+ ( extra.indexOf("?")>-1 ? "&" : "?" ) +MainElement+'='+ChildElement);
Edit:
Regexp fixed:
var clicked = "[&\\?]"+MainElement+'='+ChildElement;
And:
var extra = extra.replace(re, ""); // you can replace by regex
Edit2:
Clean up
function childboxes(MainElement, ChildElement){
var extra = window.location.pathname + window.location.search;
var regex = new RegExp("[&\\?]"+MainElement+'='+ChildElement, 'g');
extra = extra.replace(regex, "");
extra = extra+ ( extra.indexOf("?") > -1 ? "&" : "?" ) +MainElement+ '=' +ChildElement;
window.history.pushState(null, null, extra);
}
Edit3:
replaceState
function childboxes(MainElement, ChildElement){
var extra = window.location.pathname + window.location.search;
var regex = new RegExp("[&\\?]"+MainElement+'='+ChildElement, 'g');
var isReplace = extra.match(regex);
extra = extra.replace(regex, "");
extra = extra+ ( extra.indexOf("?") > -1 ? "&" : "?" ) +MainElement+ '=' +ChildElement;
window.history[isReplace?'replaceState':'pushState'](null, null, extra);
}
Upvotes: 2