• Advertisement
Sign in to follow this  

[web] Javascript question

This topic is 4218 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

how to do this in javascript (sorry, uber noob here): instead of:
<a href="somepage.html">Click Me</a>
I wish to use javascript in the href tag:
<a href="javascript:somefunction()">Click Me</a>
i searched google, and i could only find examples that would pop up a new window (window.open()) with sompage.html on the new window. I wish for the current window to load sompage.html, not on a new window. The reason is because I wish to generate random links to it. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
The html still references to another page, i believe you have to catch the OnClick, OnOver events etc,

The best place for learning this stuff is

w3schools

Hope that helps,

Dave

Share this post


Link to post
Share on other sites
Use window.location

Example:


<html>
<body>
<script>
function myfunction()
{
window.location = 'http://www.gamedev.net';
};
</script>

<a href="javascript:myfunction()">Click Me</a>

</body>
</html>

Share this post


Link to post
Share on other sites
I highly recommend you do not use javascript:

Most people don't know what javascript: does - javascript: runs the code after the :, then loads a document containing HTML which is its output (return value).

The only way of avoiding this is returning the value "void".

This is not a good idea, as on many browsers it creates race conditions, i.e. the browser is trying to load a blank page (with "" as its HTML), simultaneously it tries to load something else. One of them wins, but it's not necessarily always the same one.

Instead, use


<a href="mypage.html" onclick="return SomeClickFunc()">My funky link</a>
<script type="text/javascript">
function SomeClickFunc() {
window.location.href = "whatever.html";
return false; // suppress the original function of the click event.
}
</script>


Which is much more sound - and will go to mypage.html if javascript is disabled or fails. Also use this for popups, with the appropriate URL in the href- even if JS is enabled, this gives you the added advantage that the link will be marked as "visited" appropriately so that CSS selectors like a:visited apply to it.

Mark

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement