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 - #
var querystring = '#country=' + countrySelected;
It's used heavily in single page applications, because it doesn't redirect.
To properly navigate to fragment you need a target element, marked with and id
or name
attribute you reference in the anchor. To be precise, following a link with #foo
will scroll the element with id="foo"
or else the element with name="foo"
.
Note: the recommendation is to not use the name
attribute for this purpose. Virtually all browsers will support navigating to an element by its id
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:
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:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
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:
function supports_history_api() {
return !!(window.history && history.pushState);
}
The idea is that window.history
and history.pushState
wouldn't have been defined in a browser that doesn't support the History API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With