Reputation: 827
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>
Upvotes: 1
Views: 1353
Reputation: 298266
$('a')
looks for <a>
elements, but the DOM isn't ready. Use $(document).ready()
to create a callback function that gets triggered when the DOM is actually ready:
$(document).ready(function() {
$('a').click(function(){
alert('a');
})
})
Upvotes: 2
Reputation: 16718
The element doesn't exist when you try to bind .click
, as the page has not yet finished loading.
another thing If i am using document .ready then it is working
Well, this is exactly what $(document).ready
is for:
$(document).ready(function()
{
$('a').click(function()
{
alert('a');
});
});
Alternatively, you could use .on():
$(document).on('click', 'a', function()
{
alert('a');
});
which binds to the entire document instead, and so will work for any elements added in the future.
Upvotes: 3
Reputation: 4809
Because script is getting called before a is loaded in DOM. At that point, it doesn't see any 'a' elements to attach click elements. Though function declaration is ok, but it must be called after 'a'.
document.ready function calls the script after all elements of the page are loaded, so it gets fired.
Upvotes: 0
Reputation: 101700
The most likely issue is that jchand() is executing before the <a>
element exists. Try this:
<script type="text/javascript">
$(function(){
$('a').click(function(){
alert('a')
})
});
</script>
Upvotes: 1
Reputation: 44215
Your script executes before the DOM is ready. It will work if you call the function on document ready ($(document).ready(function())
or $(function())
) like this:
<head>
<script type="text/javascript">
function jchand(){
$('a').click(function(){
alert('a')
})
}
$(function() {
jchand();
})
</script>
</head>
<body>
<a href="#" >click me</a>
</body>
Upvotes: 0