Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger on URL change in jQuery?

Tags:

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?

like image 540
Tarida George Avatar asked Sep 10 '12 10:09

Tarida George


People also ask

What is trigger change in jQuery?

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.

What is $() in jQuery?

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)

How can I change my URL in jQ?

We can switch the URL by inputting the following jQ code: $(document). ready(function() { $('p. first a').

How can I get URL in jQuery?

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.


1 Answers

That would be a hashchange event, so I'd suggest:

$(window).on('hashchange', function(e){     // do something... }); 

JS Fiddle demo.

References:

  • on().
like image 76
David Thomas Avatar answered Dec 30 '22 16:12

David Thomas