JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Our form -->
<form id="test" action="javascript:void()" method="post"></form>
<!-- Clickable object. This can be anything -->
<button id="dispatchEvent">Test form</button>
<!-- The content of this div will change when the event is fired -->
<div id="output">
</div>
CSS
/* Not necessary to style anything but I like pretty things. */
* { margin:0; padding:0; }
body {
padding: 5px;
}
button {
background : #e0e0e0;
border: 1px solid #ccc;
border-bottom-color: #bbb;
box-shadow : 0 15px 0 rgba(255,255,255,0.35) inset, 0 2px 2px rgba(0,0,0,0.1), 0 -2px 5px rgba(0,0,0,0.15) inset;
color : #333;
text-shadow : 0 1px 0 white;
font: 300 16px 'segoe ui', sans-serif;
border-radius : 4px;
margin: 15px 0;
padding: 6px;
cursor: pointer;
}
#output {
background: #e7e7e7;
border: 1px solid #ccc;
padding: 40px 10px 10px;
color: #333;
font: 300 16px 'segoe ui', sans-serif;
text-shadow: 0 1px 0 white;
position : absolute;
top : 100px;
bottom : 5px;
right: 5px;
left: 5px;
overflow: auto;
}
#output:before {
content: "Output:";
background: #eee;
padding : 4px;
position: absolute;
top: 5px;
left: 3px;
border: 1px solid #bbb;
box-shadow : 0 5px 1px -3px #ccc;
z-index:2;
}
JavaScript
// Cache some DOM objects for use
var output = document.getElementById('output'),
form = document.getElementById('test'),
button = document.getElementById('dispatchEvent'),
// Will change the content of #output if the form gets submitteed
showFormResult = function (e) {
e.preventDefault();
output.innerHTML += 'Your form was programmatically submitted :\)<br>\n';
},
// The magic. This is where the event is created and submits the form
myEvent = function () {
// Creating the event
var event = new Event('submit', {
'view' : window,
'bubbles' : true,
'cancelable' : true
});
// Add the event listener to the form
form.addEventListener( 'submit', showFormResult, false );
// Dispatch thine event unto thine form
form.dispatchEvent( event );
},
// Add event listener to the button
init = (function () {
button.addEventListener('click',myEvent,false);
}());