6

I need to get an overlay to slide down based on what the URL has at the end of it.

If (URL has 'faq' at the end) { overlay comes down }

How can you do that in jQuery/JavaScript?

Thousand
  • 6,562
  • 3
  • 38
  • 46
Aessandro
  • 5,517
  • 21
  • 66
  • 139

4 Answers4

15

If your URL looks something like this http://yourdomain.com/faq, you could do something like this:

var url = window.location.href;
var lastPart = url.substr(url.lastIndexOf('/') + 1);

if (lastPart === "faq") {
   // Show your overlay
}

This would make it possible to check for other endings and act on them as well.

Update:

To get it working, even if the URL has a trailing slash, you could create a function like this:

function getLastPart(url) {
    var parts = url.split("/");
    return (url.lastIndexOf('/') !== url.length - 1 
       ? parts[parts.length - 1]
       : parts[parts.length - 2]);
}

You could then call the function like getLastPart(window.location.href) to get the last part of the URL for the current page.

Here is a working example as well: http://jsfiddle.net/WuXHG/

Disclaimer: If your URLs use hashes at the end, or a querystring, you would have to strip the from the URL first, for this script to work properly

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
11

You should be able to use the window.location object for this with a regexp, something like this:

/faq$/.test(window.location)

If you want to match just the path regardless of query string or hash:

/faq$/.test(window.location.pathname)
complex857
  • 20,425
  • 6
  • 51
  • 54
6

A new method endsWith() has been added to the ES6 specification. For previous versions we can polyfill it using

if (!String.prototype.endsWith)
  String.prototype.endsWith = function(searchStr, Position) {
      // This works much better than >= because
      // it compensates for NaN:
      if (!(Position < this.length))
        Position = this.length;
      else
        Position |= 0; // round position
      return this.substr(Position - searchStr.length,
                         searchStr.length) === searchStr;
  };

Now you can easily write

If (window.location.href.endsWith("faq")) { 
   // Show your overlay
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

Abdul Rauf
  • 5,798
  • 5
  • 50
  • 70
1

You can get the current URL using :

 var currentUrl = window.location.href;

Then you can use indexOf to check if your token is in the end of string (here faq)

 if (currentUrl.indexOf('faq') == currentUrl.length - 3)
 {
  // Do something here
 }
Pierre
  • 1,274
  • 1
  • 9
  • 14