Posts

Showing posts with the label Dom Events

Capturing Window.onbeforeunload

Answer : You have to return from the onbeforeunload : window.onbeforeunload = function() { saveFormData(); return null; } function saveFormData() { console.log('saved'); } UPDATE as per comments, alert does not seem to be working on newer versions anymore, anything else goes :) FROM MDN Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog() , window.alert() , window.confirm() , and window.prompt() methods may be ignored during this event. It is also suggested to use this through the addEventListener interface: You can and should handle this event through window.addEventListener() and the beforeunload event. The updated code will now look like this: window.addEventListener("beforeunload", function (e) { saveFormData(); (e || window.event).returnValue = null; return null; }); There seems to be a lot of misinformation about how to use this event going around (even in upvoted answer...

Change 's Option And Trigger Events With JavaScript

Answer : Unfortunately, you need to manually fire the change event. And using the Event Constructor will be the best solution. var select = document.querySelector('#sel'), input = document.querySelector('input[type="button"]'); select.addEventListener('change',function(){ alert('changed'); }); input.addEventListener('click',function(){ select.value = 2; select.dispatchEvent(new Event('change')); }); <select id="sel" onchange='alert("changed")'> <option value='1'>One</option> <option value='2'>Two</option> <option value='3' selected>Three</option> </select> <input type="button" value="Change option to 2" /> And, of course, the Event constructor is not supported in IE. So you may need to polyfill with this: function Event( event, params ) { params = params || { bub...