-4

Newer to javascript and trying to learn why this works, searching Google has led to no answers (although I maybe searching using the incorrect terms).

I'm am making a call to a function during an onclick event within an <a></a>. I was able to get the function finally working (with a suggestion from a coworker) by adding in 'javascript:' before making the function. Without the javascript: portion in the onclick, my function was not being called upon.

It now works but I don't understand what that is doing, the other programmer who suggested putting it in the call also isn't sure what exactly it does.

Here is a simplified version of the code used:

#1 .jspf higher up which includes page #2 to display it's contents
function createTagging(1, 2) {
    cmCreateElementTag(1 + ", " + 2,"TagName");
}


HTML in .jspf file #2 further down website makes the call to function in file #1
<a id="CatEntry" href="https://aurl"
                onclick="javascript: createTagging('parameter1', 'parameter2');"
                title="atitle" aria-label="alabel">

                <img id="ThumbNailImage_59244" src="https://image.jpg" 
                alt="" border="0"/>

        </a>

-Troy

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Troy
  • 13
  • 5

2 Answers2

4

Why do I need 'javascript:' in the call to my javascript function?

You don't. It's an onclick handler. You use the javascript: pseudo-protocol where a URL is expected (for instance, if you'd used href instead of onclick). onclick expects JavaScript code.

In fact, it only works because JavaScript has labelled statements, and javascript: is a valid label. It's completely ignored.

Without the javascript: portion in the onclick, my function was not being called upon.

With respect, that must have been observational error. Again, in an onclick handler, it makes no difference whether you have javascript: in front of it or not. If it wasn't working, and then it was working, you changed something else at the same time you added javascript:.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    "an onclick handler, it makes no difference whether you have javascript: in front of it or not. " Thanks T.J. that was my understanding as well. Perphaps I did make an additional change that I over looked. Thanks for the fast reply. – Troy Aug 17 '17 at 15:27
2

onclick attribute is always calling javascript in HTML.

onclick="createTagging('parameter1', 'parameter2');"

It is only necessary if you use not an event, but href. There you need to add the protocoll as well for Javascript.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392