Examples‎ > ‎

How to fire the onclick event

To fire the onclick event on a specified HTML element you can use the following way:

HTMLElement div = (HTMLElement) browser.getDocument().getElementById("eventDiv");
div.fireEvent("onclick", new EventObjectFactory() {
    public EventObject create() {
        EventObject eventObject = new EventObject();
        eventObject.setButton(2);
        eventObject.setClientX(15);
        eventObject.setClientY(15);
        return eventObject;
    }
});
The complete sample that shows how to fire the click event on a specified DIV element:
package dom.event;
 
import com.jniwrapper.win32.ie.Browser;
import com.jniwrapper.win32.ie.WebBrowser;
import com.jniwrapper.win32.ie.dom.EventObject;
import com.jniwrapper.win32.ie.dom.EventObjectFactory;
import com.jniwrapper.win32.ie.dom.HTMLElement;
 
import javax.swing.*;
import java.awt.*;
 
/**
 * This sample shows how to fire the click event on a specified DIV element.
 */
public class FireEventSample {
    private static final String HTML_CONTENT =
            "<html><head><script>" +
                    "function clickHandler(elem) { " +
                    "alert('clicked on element: ' + elem.tagName + " +
                    "', x = ' + event.clientX + " +
                    "', y = ' + event.clientY + " +
                    "', button = ' + event.button); }" +
                    "</script></head><body>" +
                    "<div id=\"eventDiv\" style='background: #cccccc; width:400; " +
                    "height:300' onclick=\"clickHandler(this)\">" +
                    "Click on the DIV element to display alert</div>" +
                    "</body></html>";
 
    public static void main(String[] args) {
        WebBrowser browser = new Browser();
 
        JFrame frame = new JFrame("JExplorer: Fire Event Sample");
        frame.getContentPane().add((Component) browser, BorderLayout.CENTER);
        frame.setSize(750, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
 
        browser.setContent(HTML_CONTENT);
        browser.waitReady();
 
        HTMLElement div = (HTMLElement) browser.getDocument().getElementById("eventDiv");
        div.fireEvent("onclick", new EventObjectFactory() {
            public EventObject create() {
                EventObject eventObject = new EventObject();
                eventObject.setButton(2);
                eventObject.setClientX(15);
                eventObject.setClientY(15);
                return eventObject;
            }
        });
    }
}