2

I have a JS function that I want to automatic click in a jquery.click link when page loads.

How can I make it work?

Fiddle

When page loads I want to see the alert, no click in the link needed.

js:

window.onload = function(){
document.getElementsByClassName("c").click();
}


$(".c").click(function(){
    alert("ok");
});

html:

<a href="#" class="c">test</a>
1
  • 1
    you need to attach click event before use of trigger Commented Oct 27, 2015 at 13:07

6 Answers 6

1

you need to attach click event before trigger event.

DEMO

Change

document.getElementsByClassName("c")

to

document.getElementsByClassName("c")[0]

Use Below code

$(document).ready(function(){
      $(".c").click(function(){
         alert("ok");
      });
 });

 window.onload = function(){
      document.getElementsByClassName("c")[0].click();
      // Or use jQuery trigger 
      // $(".c").trigger('click') 
 }
Sign up to request clarification or add additional context in comments.

Comments

1

DEMO HERE

trigger click on document.ready

$('document').ready(function(){
    $(".c").click(function(){
        alert("ok");
    });
    $('.c').trigger('click');
});

Comments

1

Trigger event right after you create handler

$(function(){
    $(".c").click(function(){
        alert("ok");
    }).click();
});

DEMO

Comments

1

Try this way

$(document).ready(function(){
 $(".c").trigger('click');
});

Comments

1

getElementsByClassName Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node.

To assign a click handler, either you will have to iterate through nodelist or just assign event to first element

Try this:

window.onload = function () {
    document.getElementsByClassName("c")[0].click();
};
$(".c").click(function () {
    alert("ok");
});

Comments

1

So you can push your alert into a function :

function callAlert() {
   alert('a');
}

And you can change the event click like this :

$(".c").click(callAlert);

Finally you can call the alert function when page loads like this :

$('document').ready(function(){
    callAlert(); // call here
});

Code :

$('document').ready(function(){
    callAlert(); 
    $(".c").click(callAlert);
});

function callAlert() {
    alert('a');
}

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.