Ruth Young
Ruth Young

Reputation: 888

Event handler to run jQuery based on URL

Is there a jQuery event handler that runs a script if the page has a certain URL? Similar to $( document ).ready(function() { but only if the page has a particular URL.

I want to run a script when the page is ready but only for a page with URL '.../something/somethingelse/'.

The view has links that redirect to new URLs to change layout aspects - but it's the same view (I'm using django web framework)

Upvotes: 3

Views: 1178

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

You can use window.location like below:-

An example:-

if(window.location.href =='http://stacksnippets.net/js'){
  console.log(window.location.hostname);
  console.log(window.location.href);
}else{
  $('#getHostNameandHref').html(window.location.hostname +'----'+window.location.href);
  console.log('other page');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="getHostNameandHref"><div>

Note:- you can check console.log(window.location); to see what available options are there which you can use.Thanks

Upvotes: 3

Related Questions