RGS
RGS

Reputation: 4253

JS click in a Jquery function on load

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>

Upvotes: 2

Views: 94

Answers (6)

R3tep
R3tep

Reputation: 12864

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

Upvotes: 1

Nishit Maheta
Nishit Maheta

Reputation: 6031

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') 
 }

Upvotes: 1

Rayon
Rayon

Reputation: 36609

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

Upvotes: 1

Mukesh Kalgude
Mukesh Kalgude

Reputation: 4844

Try this way

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

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

Trigger event right after you create handler

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

DEMO

Upvotes: 1

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

DEMO HERE

trigger click on document.ready

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

Upvotes: 1

Related Questions