Daniyal Javani
Daniyal Javani

Reputation: 235

window.open is javascript or html?

<input type="button" onClick="window.open('newstudent.php');"/>

This code works correctly, without script tag, why?

Upvotes: 1

Views: 103

Answers (2)

Ghostman
Ghostman

Reputation: 6114

In an element's inline event handler, like onclick, onchange, onsubmit, etc., you do not need the javascript: prefix - the reason you often see it is because people confuse it with the href syntax that I explain below. It doesn't cause an error - I believe it is interpreted as a label - but it is unnecessary.

It doesn't matter whether you want to call a function or run a "simple" JS statement, either way don't include javascript: - that is, all three of these are valid:

onclick="doSomething('some val');"
onclick="return false;"
onclick="doSomething(); doSomethingElse(); return false;"

If you are using inline event attributes don't use the javascript: prefix.

(I say "if you are using inline event attributes" because this practice is really outdated: it is better to assign the event handlers using JS in a script block.)

You only need the javascript: prefix when you want to run JavaScript from an <a> element's href attribute like this:

<a href="javascript: someFunc();">Whatever</a>

That is because the browser normally expects the href to contain a URI, so the javascript: prefix tells it to expect JS code instead. However, I don't recommending doing that because the page won't work for people who have JS disabled. Better to include an href that directs the user to a page telling them to enable JS, and include an onclick to do the JS functionality:

<a href="/enableJS.html" onclick="doSomething(); return false;">Whatever</a>

That way the link does something useful for users whether they have JS enabled or not. The return false at the end of the click handler prevents the default behaviour for a click (which would be to navigate to the specified URL).

Upvotes: 1

alex
alex

Reputation: 490183

The onclick attribute works more or so like this JavaSript.

input.onclick = function() {
    // The code from the value.
};

There is no requirement that the script element be present to run JavaScript. Some browsers are/were even stupid enough to execute JavaScript via CSS.

Upvotes: 1

Related Questions