Reputation: 3920
I have this simple HTML page:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
<script>
$(document).ready(function () {
$('#test').click();
});
</script>
</head>
<body>
<a id="test" href="http://google.com">http://google.com</a>
</body>
</html>
I want to trigger a click event on the element called test
on loading the page. The actual code is actually more sophisticated than that but this very basic example is not working. I checked the console log and there are no notices there.
Upvotes: 1
Views: 79
Reputation: 2599
Here click event is triggered i.e. click event is fired on page load but you can not load href by just triggering the click event,for that you can use
window.location.href = "http://www.google.com";
Upvotes: 0
Reputation: 133403
You need to use to trigger the DOM element click
$('#test').get(0).click();
Use .get(), It retrieve the DOM elements matched by the jQuery object. As .click()
will trigger the element click event handler. It will not actually click the element.
Using simple Vanialla JS
document.getElementById('test').click()
Upvotes: 2
Reputation: 18873
The .click()
you are triggering is correct but you are missing a click event for '#test'
as shown :
$('#test').click(function(){
alert('here');
});
Now your complete jquery code is as shown :
<script>
$(document).ready(function () {
$('#test').click(); //or $('#test').trigger('click');
$('#test').click(function(e){
e.preventDefault();
alert('here');
window.location.href = $(this).attr('href'); //redirect to specified href
});
});
</script>
Upvotes: 2
Reputation: 135
Your #test link should be bound to a function, eg:
$(document).ready(function () {
//do something on test click
$('#test').on("click", alert());
//click test
$('#test').click();
});
Upvotes: 1
Reputation: 3555
.click() doesn't actually send a click event.
What .click() does is define something that happens when you click on the element.
Upvotes: 2