window resize hover animation

window resize hover animation

Hello!
I'm trying to create a custom responsive accordion menu that animates when you hover over it, but when sized down to mobile, changes to a clickable grid.

I think I have the majority of the work done, but cannot seem to nail the window.resize() handler. I feel like I need a way to stop the resize handler from calling, once the if statement is met. But, I'm not a jQuery master, thus I am having trouble figuring out how to properly write the syntax.

You can find a link to the example here:

And this is the code (also at the bottom of the html):

<script>
var $li = $('.accordion li'),
$width = $(window).width();

$(function() {

if($width >= 640) {
$li.hover(function() {
$(this).next().animate({marginLeft: "0"});
}, function() {
$(this).next().animate({marginLeft: "-15.5%"});
});
} else {
$li.stop(true, false);
$li.css({marginLeft: "0"});
};

$(window).resize(function() {
var $newWidth = $(window).width();

if($newWidth <= 640) {
$li.css({marginLeft: "0"});
$li.off();
$(window).off('resize');
} else if ($newWidth > 640) {
$li.css({marginLeft: "-15.5%"});
$li.hover(function() {
$(this).next().animate({marginLeft: "0"});
}, 
function() {
$(this).next().animate({marginLeft: "-15.5%"});
});
$(window).off('resize');
}
});

});
</script>


Many thanks in advance!
Casey Baggz