Lol, you have improper button assignment. In short, what you code says is:
On document load, if the window is less than 480, then tell the button click event to always animate top 50px. But, if (document.onload) the window is less than 1024, then the button click event should always animate to the left 50px.
You need to move you if statement inside your event call like so:
$(function() { // Same as $(document).ready, just shorter. Personal pref
$('button').on('click', function(e) {
if ($(window).width() <= 480) {
$(this).animate({top: '50px'})
}
else if ($(window).width() < 1024) {
$(this).animate({left: '50px'})
}
});
})
Now the next question is, are you sure about those if statements on window size? What is your exact aim?
How you could make use of $.resize with a debounce to keep it from firing over and over.
/** resize(event)
* Actual method called when done resizing.
**/
function resize(e) {
var w = $(window).width();
switch (true) {
case (w <= 480):
// do work
// window is now 480 or less
console.info('Window.width is less than or equal to 480');
break;
case (w <= 1024):
// do work
// window greater than 480 but less than 1024
console.info('Window.width is less than or equal to 1024');
break;
default:
console.info("window.width = " + w);
}
console.debug( "Resize method finished funning:\t", { $this: this, $eventArg: e } );
}
/** onResize(event)
* Called whenever window is resize.
* This acts as a buffer between the multiple times resize is fired and the resize method being fired.
**/
function onResize(e) {
this['__debounce_timer__'] && clearTimeout(this['__debounce_timer__']);
this['__debounce_timer__'] = setTimeout($.proxy(resize, this, e), 250);
}
// Same as window.addEventListener('resize', onResize); resize(new Event('resize', {}));
$(window).on('resize', onResize).trigger('resize');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>