I am trying to add country name for every link in page my website. It is redirecting two times. How can I change URL without redirecting?
$(document).on('click',function(e){
var querystring = '?country=' + countrySelected;
if(e.nodeName === "A"){
window.location = window.location.href +querystring;
}
});
Use the hash tag - #
It's used heavily in single page applications, because it doesn't redirect.
Navigate to fragment
To properly navigate to fragment you need a target element, marked with and
id
orname
attribute you reference in the anchor. To be precise, following a link with#foo
will scroll the element withid="foo"
or else the element withname="foo"
.Note: the recommendation is to not use the
name
attribute for this purpose. Virtually all browsers will support navigating to an element by itsid
attribute. Except, perhaps, old Netscape 4 (1997), IE4 (1997) or older browsers, can't test this. Making an hyperlink to a position in the page was already present in the RFC1866 of 1995.The found element will also be made active. That implies that you can apply css to it by using the pseudo selector
:active
.CSS3 also defines the pseudo selector
:target
to be applied on the target element.Browser compatibility for the target pseudo selector:
History API
If navigating to fragment isn't good enough for you, consider using the history API. I'm Taking this example from the MDN:
Suppose http://example.org/foo.html executes the following JavaScript:
This will cause the URL bar to display http://example.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
Read more at diveintohtml5.info and css-tricks.com.
Browser compatibility for History API:
Dive Into HTML5 suggests the following method to detect compatibility:
The idea is that
window.history
andhistory.pushState
wouldn't have been defined in a browser that doesn't support the History API.Does the webpage do something different if you are in a different country? If it does, then it would require the browser to load the page that is for the selected country(thereby requiring a redirect). If the webpage does something different for the selected country, but it requires another parameter to actually do something that requires a country-specific addition to the URL, then you would be better off with something like:
You can use history API
https://developer.mozilla.org/en/docs/Web/API/History
Ref: https://css-tricks.com/using-the-html5-history-api/