Grow your CSS skills. Land your dream job.

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

  • # December 3, 2012 at 12:56 am

    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?

    # December 3, 2012 at 1:51 am

    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.

    # December 3, 2012 at 3:58 am

    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)

    # December 3, 2012 at 3:42 pm

    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

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".