You can do so much with window.location.href
and check the URL, for example:
if ( !!location.href.match("https?:\/\/pt.stackoverflow.com\/?$") ) {
alert("Página inicial")
}
Or you can do with window.location.pathname
and check the path of the URL, for example:
if ( !!window.location.pathname.match("(?:\/|index\.(?:php|asp|html?))$") ) {
alert("Página inicial")
}
Explanation of Regex 1:
https?:\/\/pt.stackoverflow.com\/?$
└┬┘ └─┬─┘
│ └──── Informa que a URL tem que terminar com `/`. / ou /
└───────────────────────────────── Informa que o `s` como opcional. Isso serve tanto para http://, quanto https://
Explanation of Regex 2:
(?:\/|index\.(?:php|asp|html?))$
└┬┘ └───────────┬──────────┘
│ │
│ │
│ └──────────────── ou terminar com index.php; index.asp; index.html; ou index.htm
└─────────────────────────────── Informa que o `path` deve terminar com `/`
The !!
serves to convert the result to boolean.
If you want something much simpler, you can use slice
, for example:
if (location.pathname.slice(-1) === "/") {
alert("Página Inicial");
}
Felipe, I think, if you want the behavior to only fire on the home page, you could use
if (window.location.href === '/')
on line two, before connecting the function click on the element.– Rafael Araújo