I was reading the OReilly JavaScript-the definitive guide and it its first chapter he was showing this code and i really don't understand it and how could this code work with omitting <HTML>, <head>, and <body> tags in my HTML file

javascript:5%2
javascript:x = 3; (x > 5)? "x is less": "x is greater"
javascript:d = new Date(); typeof d;
javascript:for(i=0,j=1,k=0,fib=1; i>5; i++,fib=j+k,k=j,j=fib) alert(fib);
javascript:s=""; for(i in navigator) s+=i+":"+navigator[i]+"\n"; alert(s);
  • Can you provide some more context on this? Darryl Hein about 7 years ago

2 answers

Aaron 45
1
point

It is called Bookmarklet in JS world. It works because javascript: prefix will tell your browser which protocol your browser use :

for example : http://www.example.com, http is a protocol name and browser knows that www.example.com address uses http protocol

so javascript: is an also protocol when writing like that javasript:alert("hello")

<a href="javascript:alert('hello')" />

means when user clicks on this link, run alert.

More information : The "javascript:" Protocol and also here is a piece of information from MSDN : http://msdn.microsoft.com/en-us/library/aa767736%28VS.85%29.aspx

Answered about 7 years ago by Aaron
0
points

Hi there

these codes can be placed in the href attribute of an anchor link.

Example: <a href="javascript:alert('Coolness');">Click here.</a>

Try this in a HTML file, you'll notice that when you click on the link, the javascript code after javascript: runs.

Answered about 7 years ago by Sam Yong