0

I have a button in HTML:

 <button type="button" id="id" onClick="function()">text</button>

The function simply alters the CSS and text of some HTML elements.

How do I, by default every time the page loads, "click" on the button with Javascript, without the user having to click on the button first?

Thanks in advance.

  • Don't click the button, run the function. [Run Code on Page Load](http://stackoverflow.com/a/4842622/1669208) – Dan Grahn Nov 26 '13 at 13:33

6 Answers6

1
$(function(){

  $('#id').trigger('click');

});

But you should not use intrusive javascript, better do:

<button type="button" id="id" >text</button>

...

$(function(){

  $('#id').click(function(e){

    // your code here

  }).trigger('click');

});
moonwave99
  • 19,895
  • 2
  • 38
  • 62
1

Using jQuery you can do this :

$('#id').click();

http://api.jquery.com/click/

leaf
  • 14,210
  • 8
  • 49
  • 79
0

function is a reserved keyword. It is an error, so make some name onClick="function clickEvent()"

<script>
function clickEvent() {
   alert("I'm clicked");
}
</script>
Praveen
  • 50,562
  • 29
  • 125
  • 152
0

You can use jquery to do this very easy: // every thing is loaded

 $(function(){
      $('#id').click();
    });
Ringo
  • 3,436
  • 2
  • 20
  • 36
0

Don't click the button, run the function.

$(document).ready(function() {
  $('#id').click();

  // Or

  click_function();
});
Dan Grahn
  • 8,166
  • 3
  • 33
  • 67
0
window.onload=function;

function would be the name of your function. You don't need to click, you just need to run the function.

Jaiesh_bhai
  • 1,688
  • 8
  • 24
  • 38