Skip to content

Instantly share code, notes, and snippets.

@mohamedmansour
Created April 15, 2012 18:26
Show Gist options
  • Save mohamedmansour/2394247 to your computer and use it in GitHub Desktop.
Save mohamedmansour/2394247 to your computer and use it in GitHub Desktop.
Override the Resize Event from a given site, so you can reuse it and dispatch it!
/**
* Overrides the Resize Event handler if exists so we can call that resize callback.
* This is useful if websites relayout on resize events in case you are changing the
* DOM. Or perhaps doing some animations.
*
* @usage
* // Whenever your ready, it is best to inject this at the beginning.
* ResizeHijack.inject();
*
* // Then you fire the resize event and if that website has any resize it will call it.
* ResizeHijack.fire();
*
* @author Mohamed Mansour http://mohamedmansour.com
* @license MIT
*/
ResizeHijack = (function() {
// INJECT the overriden resize handler to the DOM
var resizeInject = function() {
var resizeCallback = null;
var resizeEvent = document.createEvent('Event');
resizeEvent.initEvent('resizeEvent', true, true);
var _addEventListener = window.addEventListener;
window.addEventListener = function() {
if (arguments[0] === 'resize') {
resizeCallback = arguments[1];
}
_addEventListener.apply(window, arguments);
};
window.addEventListener('resizeEvent', function(e) {
resizeCallback(e);
});
};
return {
// Fire a resize event, this will call the resize callback defined in that site.
fire: function() {
var resizeEvent = document.createEvent('Event');
resizeEvent.initEvent('resizeEvent', true, true);
window.dispatchEvent(resizeEvent);
},
// Inject the script in the context of the webpage so we can override
// the resize behavior.
inject: function() {
var script = document.createElement('script');
script.setAttribute('id', 'inject-area');
script.appendChild(document.createTextNode('(' + resizeInject + ')();'));
document.body.appendChild(script);
return this;
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment