How can I detect with javascript if the attribute "#" is added to the url?

How can I detect with javascript if the attribute "#" is added to the url?

I need a cross browser solution. I am currently using the following code, but it only works in Firefox:

if ((window.location.hash) || (window.location.hash != "#"))
    window.scrollBy(0,-60);

thank

+3
source share
4 answers

The following line should do the job for you:

if(!!window.location.hash) // if 'true' you have an appending hash
     window.scrollBy(0,-60);

According to w3schools it location.hashshould work in all major browsers.

+1
source

Firstly, there is an error in your published code. If you intend to use a common template string is neither null nor empty nor '#', this should be:

if (window.location.hash && window.location.hash != "#")
    window.scrollBy(0,-60);

However, since Location.hash is well supported, the code above should work on all modern browsers.

+3
source

, hash , , :

var url = window.location.href;
var hashLoc = url.lastIndexOf('#');
if(hashLoc > -1 && hashLoc < url.length )
     window.scrollBy(0,-60);
+1

For good cross-browser support, you can refer to jQuery. This may be redundant for your project, but overall it greatly simplifies js development. There is an excellent hashchange plugin that I have used with great success for several months.

0
source

Source: https://habr.com/ru/post/1790314/


All Articles