Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Destroy jQuery function

Hi

I only want this piece of code to run on tablets and mobile. I'm already using enquireJS but I can't get it to work that way. If the browser window is less than 1200px it should run, but if the user increases the browser beyond that then the code should stop running. Do I need to wrap it in a function and then refer to it that way? I'm vaguely aware that it may have something to do with destroying the function and declaring it null or something.

$('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
                'scrollTop': $target.offset().top
        }, 900, 'swing');
      });

1 Answer

Steven Parker
Steven Parker
229,732 Points

Why not just have the function do nothing if the screen size is above your limit?

You could do a lot of work to enable and disable the event triggering, but if you just put a test for size and return at the top of the event hander (perhaps right after preventDefault), you could just ignore the events when the code should not be executed:

    if (window.matchMedia("(min-width: 1200px)")) return;

Just be sure this function is supported in your browser.