Dan Dan - 4 months ago 5x
Javascript Question

jQuery trigger function above a certain window width

I'm having a lot of problems with some jQuery I'm trying to write. I need one function to be available all the time, and one function to be available when the users window is greater than a set width. Here are my functions, both running in


Function for drop down menus, should only happen when the window is larger than set amount;

//the dropdown code for desktop users
function largeDropDown(){
$('#nav ul li').hover(
function(){ $(this).find('ul').stop().slideDown(300); },
function(){ $(this).find('ul').stop().slideUp(300); }

And this one is available all the time, although it would be nice to know how to make this one conditional to the screen size also.

//the dropdown code for smaller screens
function openMenu(e){
} else {


Using CSS media queries, the
is hidden when the window is over 768px. That way the jQuery won't do anything (at least that's my attempt at getting this to work!)

So, I'd like to know how to make the first function work above 768px, and also how to call this functionality on a window resize. Any help would be great! Thanks.


You can bind window resize events by doing:

$(window).on('resize', function(event){
    // Do stuff here

You can get the window size by doing:

var windowWidth = $(window).width();
if(windowWidth > 768){
    // Do stuff here

Here is a jsfiddle to see it all in action.

Be careful what you bind in your window resize events. It can end up being executed dozens of times when a user naturally resize the browser. Heavy code will result in a poor user experience.