-4

For example if I have two js functions in my HTML page named func1() and func2(). My question is how can I execute func1() when someone visits /url/to/the/page#tag1 and/or similarly func2() when someone visits /url/to/the/page#tag2.

Saif
  • 2,530
  • 3
  • 27
  • 45

1 Answers1

3

it's very simple! you could have found it with just googling it but basically, you have just to use the global window hash string and according to its value you invoke the function you need:

if(window.location.hash === '#tag1') {
  func1()
} else if (window.location.hash === '#tag2'){
  func2()
}

Updated Version: (dangerous & slow)

var number = window.location.hash.split('#tag').pop(); //return 1
if(window.location.hash === '#tag' + number) {
eval("func" + number + "()");
}

you should avoid using eval as it opens security vulnerabilities and can allow attackers to run malicious code on the user's machine. You can read more about the eval function and why you should never use it on MDN docs

Hamed Baatour
  • 6,664
  • 3
  • 35
  • 47
  • 1
    And if there are 20 tags...? – Andreas Apr 07 '18 at 12:07
  • Andreas is right, this scales pretty badly – Luca Kiebel Apr 07 '18 at 12:09
  • if you have 20 tags to run 20 different functions you should be doing something wrong by design. I don't see the point to scale this and if you are still trying to do something bad like this you will end up using bad practices like the eval() function and you will end up with a pretty bad code, to say the least. – Hamed Baatour Apr 07 '18 at 12:23
  • @Andreas I edited Hamed answer, with updated version, it's kinda dynamic, I wrote it blindly, but it can be dynamic.. – Pedram Apr 07 '18 at 12:27
  • @HamedBaatour why you think `eval` is a bad practice? – Pedram Apr 07 '18 at 12:28
  • @Pedram _Your_ update won't work (which may attract downvotes... hence you should be really careful when editing someone else answer). – Andreas Apr 07 '18 at 12:36