I have some buttons on my visualforce page which onclick, run a javascript function.
Sometimes however, the javascript function will need to run without the user actually clicking on the button. I need to call the javascript function from an apex method. How can I achieve this?
Best Answer
You can reRender scripts that should be run when conditions are met. I wrote up an arbitrary example where you have (approximately) a 50% chance of getting a popup dialog, and 50% chance of just plain text. Every five seconds, the server is called again, and you may get a dialog popup. This requires no user interaction.
How it works:
Though Apex Code can't call JavaScript directly, it can set a variable to render a script block that can run arbitrary code. On each render, when the variable is true, an alert is produced. I wouldn't try doing this inside a closure or the middle of a script block, as you'll probably get very unpredictable results. You could dispatch a custom event or call some global function, if you prefer. You can use this technique anywhere reRender is supported, such as on a commandLink, commandButton, and actionFunction.