I have a button that i what to be clicked automatically after the page is loaded. I used setTimeout but it does not seem to work. What is wrong? it worked in other similar posts in stackoverflow which is where i got the idea from but for some unknown reason to me in does not work in my code
$(document).ready(function() {
jQuery(function($){
// The variable jcrop_api will hold a reference to the
// Jcrop API once Jcrop is instantiated.
var jcrop_api;
initJcrop();
// The function is pretty simple
function initJcrop()//{{{
{
// Invoke Jcrop in typical fashion
$('#target').Jcrop({
onRelease: releaseCheck,
},function(){
jcrop_api = this;
// Setup and dipslay the interface for "enabled"
$('#can_move').attr('checked','checked');
});
};
function releaseCheck()
{
jcrop_api.setOptions({ allowSelect: true });
$('#can_click').attr('checked',false);
};
$('#setSelect').click(function(e) {
// Sets a random selection
jcrop_api.setSelect([0,0,400,118]);
});
});
setTimeout(function() {
$('#setSelect').trigger('click');
},10);
});
<button id="setSelect">setSelect</button>
There might be an issue with asynchronous order of things:
eg. the
setTimeoutis popped before theclickhandler is set, or maybe after theclickhandler is set but before thejcrop_apiis set. Note that just because one line is below the other doesn’t mean it is executed later – because you don’t control when the callback that initializesjcrop_apiis called.Adding
console.loglines may be useful to debug this problem and see if the code is executed in the order you plan.To fix the order of things you can set up the click handler only after you initialize the jcrop_api, and set the timeout only after the click handler is set up (maybe you don’t need a timeout at all then).