Michael Samuel
Michael Samuel

Reputation: 3920

Jquery click function not triggering a click

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

Answers (5)

Ankit Gupta
Ankit Gupta

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

Satpal
Satpal

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()

DEMO

Upvotes: 2

Kartikeya Khosla
Kartikeya Khosla

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

Gareth Talty
Gareth Talty

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();
});

http://jsfiddle.net/ub8unn2b/

Upvotes: 1

Nzall
Nzall

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

Related Questions