-2

How can I invoke Onclick in Anchor tag only if JavaScript if enabled, in case if Javascript is disabled then execute href?

  • what do you mean by `execute href` ? – Zeeshan Ahmad Khalil Mar 04 '19 at 12:29
  • 1
    I think te OnClick will only get executed when javascript is enabled by default. How can it be executed when javascript is disabled? – yadejo Mar 04 '19 at 12:30
  • If you want to execute a js function when js is disabled then it can't be done. But you can achieve the task performed by js function by using php in ` – Zeeshan Ahmad Khalil Mar 04 '19 at 12:40
  • Sure, actually my requirement is to call a URL which should only invoke when JavaScript is disabled, else Java script function should get executed. Example: TestLink Please let me know in case if more explanation needed. – Varun Neema Mar 04 '19 at 13:14

2 Answers2

0

The JavaScript can only run if JavaScript is enabled.

The href will be followed automatically when a link is clicked on (that's the default behaviour) unless JavaScript is used to prevent it.

function onClick(event) {
  event.preventDefault();
  console.log("JavaScript function called");
}
const link = document.querySelector("a");
link.addEventListener("click", onClick);
<a href="http://example.com/">Link</a>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-2

kindly elaborate why do you want to check for java-script disable for executing href. For checking java-script disable you can refer below link for your reference.

How to detect if JavaScript is disabled?

Edit: if javascript is disabled then function written in html will fail automatically and href will gets executed. Please check with below code.

<!DOCTYPE html>
<html>
<body>

<script>
document.write("Hello World!")
function test()
{
alert('okoko');
return false;
}

</script>
<noscript>Sorry, your browser does not support JavaScript!</noscript>

<a href="http://google.com" onclick="return test();">test</a>
<p onclick="">A browser without support for JavaScript will show the text inside the noscript element.</p>

</body>
</html>

enter image description here

enter image description here

enter image description here

as per above screenshots it is confirm that href will gets executed automatically when java-script is disabled.

Hope this answer will help you.

Vikas Sonichya
  • 125
  • 1
  • 6
  • Thanks Vikas, actually I am aware of – Varun Neema Mar 04 '19 at 13:18
  • Thank you Vikas. It worked. I tried same but only thing I missed was "return" inside onclick function. – Varun Neema Mar 04 '19 at 13:52