Click event with jquery function is not working when it is before the a tag but it is working fine after the a tag. Also, if I use document.ready then it works. I would like to know why it is not working when it is before the a tag.
<head>
<script type="text/javascript">
function jchand(){
$('a').click(function(){
alert('a')
})
}
jchand();
</script>
</head>
<body>
<a href="#" >click me</a>
</body>
The element doesn’t exist when you try to bind
.click, as the page has not yet finished loading.Well, this is exactly what
$(document).readyis for:Alternatively, you could use .on():
which binds to the entire document instead, and so will work for any elements added in the future.