1

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.

8
  • you have to use $('#test').trigger("click"); Commented Sep 22, 2014 at 12:27
  • @Regent no it is if the OP wants to trigger the click event, the implementation of what has to be done resides on him Commented Sep 22, 2014 at 12:29
  • @ChakravarthySM take a look at docs to see what is going on, when you call .click() without arguments. Commented Sep 22, 2014 at 12:31
  • 1
    @Satpal partially you are right, partially I am: $('#test').get().click(); will cause an error. $('#test').get(0).click(); will not cause an error. Commented Sep 22, 2014 at 12:39
  • 1
    @Regent, Yep You are correct. I missed 0 in comment. Commented Sep 22, 2014 at 12:40

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

.click() doesn't actually send a click event.

What .click() does is define something that happens when you click on the element.

Comments

2

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>

Comments

1

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/

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.