Reputation: 4253
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?
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
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
Reputation: 6031
you need to attach click
event before trigger
event.
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
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 throughnodelist
or just assign event to firstelement
Try this:
window.onload = function () {
document.getElementsByClassName("c")[0].click();
};
$(".c").click(function () {
alert("ok");
});
Upvotes: 1
Reputation: 4844
Try this way
$(document).ready(function(){
$(".c").trigger('click');
});
Upvotes: 1
Reputation: 171669
Trigger event right after you create handler
$(function(){
$(".c").click(function(){
alert("ok");
}).click();
});
Upvotes: 1
Reputation: 29683
trigger click
on document.ready
$('document').ready(function(){
$(".c").click(function(){
alert("ok");
});
$('.c').trigger('click');
});
Upvotes: 1