How can I trigger a function when the URL changes? I try something like:
$(windows.location).change(function(){ //execute code });
So my URL is something like http://www.mysite.com/index.html#/page/1
. How can I execute jQuery or JavaScript code when the URL becomes something like http://www.mysite.com/index.html#/page/2
?
jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)
We can switch the URL by inputting the following jQ code: $(document). ready(function() { $('p. first a').
The current URL in jQuery can be obtained by using the 'href' property of the Location object which contains information about the current URL. The 'href' property returns a string with the full URL of the current page.
That would be a hashchange
event, so I'd suggest:
$(window).on('hashchange', function(e){ // do something... });
JS Fiddle demo.
References:
on()
.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