Sukhjeevan
Sukhjeevan

Reputation: 3156

Is there any difference when calling a javascript function onclick="fn1()" and onclick="javascript:fn1()"

What is the difference between calling a function directly onclick="fn1()" and onclick="javascript:fnq()"?

What would be the best approach?

Thanks

Upvotes: 0

Views: 124

Answers (3)

ruakh
ruakh

Reputation: 183476

The difference is that onclick="fn1()" means what you think it does ("run the function fn1()"), while onclick="javascript:fnq()" is using javascript: as a useless label for the statement fnq(). Note that you could also write onclick="foobarbaz:fnq()", and it would do the same thing; there's absolutely nothing special about the javascript. (You may be thinking of the use of javascript: as a URL protocol in <a href="javascript:fnq()">, where the javascript: serves the same general purpose as http: would: it indicates the type of URL.)

Of these, onclick="fn1()" is the better practice, though it's generally better to attach the click-handler from JavaScript, rather than putting it in the HTML to begin with.

Upvotes: 2

Eli
Eli

Reputation: 17825

They are functionally equivalent. Which is best? Neither. Don't mix markup and JavaScript. Instead, bind a function to your element:

<div id="element"></div>

Now there are multiple ways to do this:

// Find element
var el = document.getElementById('element');

// Option 1:
el.onclick = function() {
    fn1();
};

// Or by reference:
el.onclick = fn1;

// Option 2:
if (el.addEventListener) {
    el.addEventListener('click', fn1, false);
} else {
    el.attachEvent('click', fn1);
}

Upvotes: 2

S.P.
S.P.

Reputation: 3054

I believe that putting javascript inline has been depreciated by W3C.

Only use the inline javascript when you are trying use two different scripting languages with your event handlers.

Upvotes: 0

Related Questions