treehouse : what would you like to learn today?
Web Design Web Development iOS Development

How to run a jquery function but only when the browser window width is > 1024px?

  • This is a functionality I'd like to add to my responsive one-page website, but only when the browser width is greater than 1024px.

    My knowledge of jQuery is minimal, but this is the code I have now:

      $(document).ready(function() {
          var pageWidth = $(window).width();
          if (pageWidth > 1024) {
    
          $('.footer a').mouseenter(function() {
          $(this).effect("bounce", { times:1, distance:4 }, 250);
          });
    
          });
      });
    

    Another question, when this function isn't firing—for example when a user loads the site on a device that has < 1024px width, do they still have to load the javascript file?

  • Try this:

      $(document).ready(function() {
          var pageWidth = $(window).width();
    
          if (pageWidth > 1024) {
              $('.footer a').hover(function() {
                  $(this).effect("bounce", { 
                      times:1, 
                      distance:4 
                  }, 250);
              });
          };
      });
    

    @question about having to load the script. Yes, whether the browser runs the script or not, it will be loaded.

  • you could do:

    $(document).ready(function() { var pageWidth = $(window).width(); var body= document.getElementsByTagName('body')[0]; var script= document.createElement('script'); script.type= 'text/javascript'; if (pageWidth > 1024) { script.src= 'desktop.js'; }else{ script.src= 'mobile.js'; }; body.appendChild(script); });

    that way you only load the needed script (it makes sense if the scripts are big in filesize)

  • Thank you for your responses! I've been battling this thing all last night, but finally a buddy suggested I use CSS animation. I think it does the job pretty well. The only downside I see so far is that the animation abruptly stops if the mouse leaves the block it's applied to.

    What do you guys think? Check out the navigation- http://vitaliyg.com