Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference javascript:method() and just plain method()

I have come across the following syntax in JavaScript

<img style="padding-left:8px;" id="testIcon" align="middle" src="/images/test.png" onclick="javascript:testMethod()"/>

and was wondering what is the difference between above and

<img style="padding-left:8px;" id="testIcon" align="middle" src="/images/test.png" onclick="testMethod()"/>
like image 283
Aniket Thakur Avatar asked Mar 18 '23 20:03

Aniket Thakur


2 Answers

The use of the pseudo-protocol javascript comes from a time when it was used in the href attribute of an anchor tag:

<a href="javascript:doSomething()">Click me</a>

In the above context the javascript: pseudo-protocol gives a hint to the browser than this is a function to run, not an address to resolve.

In that context of your question:

<img src="images/test.png" onclick="javascript:testMethod()"/>

it does nothing.

The javascript: is treated as a label (a little-known part of the JavaScript language) and is harmless. Since the browser knows that onclick calls a script, nothing special is needed.

like image 173
Jeremy J Starcher Avatar answered Apr 02 '23 19:04

Jeremy J Starcher


I'd guess that the former syntax is available because some browsers support scripting languages other than JavaScript. IE supports VBScript, for instance. If you had a page containing JavaScript and VBScript functions with the same name, you could probably use that syntax to disambiguate.

like image 33
user3553031 Avatar answered Apr 02 '23 19:04

user3553031