I am trying to call a javascript function onclick. I have written something like this
<script type="text/javascript">
function readPage(){
alert("Hello");
}
document.getElementById('read').onclick=readPage;
</script>
<a id="read" href="">read</a>
I am trying to call readPage function but its not working?if I write onclick inside tag it works but the way I have written above is not working. why?
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
A commonly-used alternative to document. getElementById is using a jQuery selector which you read about more here.
The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
It will work with an empty href
attribute (then the current URL of the page will be used),
but you have to use, as already mentioned, window.onload
to attach the click handler, or you have to move the script
block after the a
element.
Otherwise getElementById
cannot find the element because it does not yet exist in the DOM tree.
<a id="read" href="">read</a>
<script type="text/javascript">
function readPage(){
alert("Hello");
return false;
}
document.getElementById('read').onclick=readPage;
</script>
As already mentioned, you use e.g. return false;
to make the browser not follow the URL. You even need this if you change the URL to href="#"
because otherwise the browser will scroll the page to the top.
Test it yourself: http://jsfiddle.net/Nj4Dh/1/
Read more about the traditional event registration model.
There is nothing wrong about how you do it, but when. You can not access the DOM (like running getElementById())
before it has loaded. The easiest thing to do is to run you code inside window.onload
like this:
window.onload = function () {
document.getElementById("read").onclick=readPage;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With