Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
220,634 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.