Magento 2 JavaScript – Custom JavaScript Not Working

javascriptmagento2requirejs

I'm trying to inject a scroll to anchor javascript globally in Magento 2.

More specifically this script:

$('a[href^="#"]').on('click', function(event) {
    var target = $(this.getAttribute('href'));
    if( target.length ) {
        event.preventDefault();
        $('html, body').stop().animate({
            scrollTop: target.offset().top
        }, 1000);
    }
});

I have taken the reference from this blog post.

I converted it to include defines and stuff:

define([
    "jquery",
    "jquery/ui"
], function ($) {
    'use strict';

$('a[href^="#"]').on('click', function(event) {
    var target = $(this.getAttribute('href'));
    if( target.length ) {
        event.preventDefault();
        $('html, body').stop().animate({
            scrollTop: target.offset().top
        }, 1000);
    }
});

});

And injecting it in to my themes default_head_blocks.xml with <link src="js/custom.js" />

The injection works but I am getting the following error in Chrome console:

Uncaught Error: Mismatched anonymous define() module: function ($) {
    'use strict';

require.js:166

Best Answer

Instead of defined use require Like this:

require([
    'jquery',
    "jquery/ui"
], function($){
    'use strict';

    $('a[href^="#"]').on('click', function(event) {
        var target = $(this.getAttribute('href'));
        if( target.length ) {
            event.preventDefault();
            $('html, body').stop().animate({
                scrollTop: target.offset().top
            }, 1000);
        }
    });
});
Related Topic