Reputation: 733
I'm new in Javascript and this is my code
<!DOCTYPE html>
<html>
<body>
<a href="http://www.example.com" id="test" onclick="example(this); return false"><img src="http://www.example.com/1/img" border="0" /></a>
<script>
function () {
document.getElementById('test').click();
};
function();
</script>
</body>
</html>
I was trying to open that link when the web page is loaded but I make some errors. Any help?
Upvotes: 2
Views: 2442
Reputation: 3734
Do it like this:
<!DOCTYPE html>
<html>
<body>
<a href="http://www.example.com" id="test" onclick="yourfunction()">asdf</a>
<script>
document.getElementById('test').onclick();
function yourfunction(){
alert("clicked");
}
</script>
</body>
</html>
What we do here is assigning the function "yourfunction()" to "onclick" of your anchor (the element). Due to the fact that your code is automatically executed when you reload the page (note that we've just posted a line of code into the script tag) you can trigger the onclick event just by using ".onclick()".
However, you're executing "yourfunction()" every time you reload the page and as you click your anchor.
The function itself is pretty boring. It just makes an alert (small window with a message and ok button) which says "clicked".
Further reading:
Some further advice. I think you are trying to achieve a "redirection" to another site as soon as you got to a domain. You probably want to do stuff like redirecting a typo ("gogole.com") to your "real" domain (google.com). This shouldn't be done with Javascript! You have to configure your webserver to do so (it's pretty easy). See this for example.
However, ther is also another approach to achieve this:
<meta http-equiv="refresh" content="0; url=http://www.example.com/">
Put this line of code into the of your document.
Upvotes: 0
Reputation: 193261
The way you define and invoke function is not correct. This is invalid syntax construction as function declaration (statement staring with function
keyword) requires a name to be valid javascript code.
So you either give function a name an invoke it:
function somename() {
document.getElementById('test').click();
};
somename();
.. or use IIFE (immediately-invoked function expression):
(function() {
document.getElementById('test').click();
})();
However, in your case you don't really need as you don't use it for what it's really useful, i.e. creating new scope. Simple line
document.getElementById('test').click();
would be just enough.
Upvotes: 1
Reputation: 1397
You don't need the example function... remove onclick="example(this)..."
. Since you are clicking via javascript, the normal function of the click is to go to the link specified in the href
attribute anyway.
If you just want to open a new link on page load, you can also remove all the body and just use the following:
<body>
<script>
window.location.assign = "http://example.com";
</script>
</body>
Upvotes: 0