1

I want to change the hash in the URL when I trigger an action (a click for instance) using a pattern like #/param-1=foo&param-2=bar

In a fresh Drupal 8 theme, when I try this, I got an error saying Uncaught Error: Syntax error, unrecognized expression: #/test=0

It works fine when I try with #param1-foo_param2-bar but I would like more flexibility. It looks like jquery is trying to consider the hash as a selector and returns an error that says it's not a valid selector.

Here is the code I use on a fresh classy based theme:

(function ($, Drupal) {
    Drupal.behaviors.myModuleBehavior = {
        attach: function (context, settings) {
            $('.layout-container', context).once('myModuleBehavior').each(function () {
                $('.site-name a').on('click', function (event) {
                    event.preventDefault();
                    event.stopPropagation();
                    console.log("clicking on logo");
                    window.location.hash = "/test=0";
                });
            });
        }
    };
})(jQuery, Drupal);

And here is the result I get from chrome console:

Uncaught Error: Syntax error, unrecognized expression

closed as off-topic by Kevin, Pierre.Vriens, leymannx, mradcliffe, sanzante Jun 17 '18 at 0:48

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions on programming, PHP, SQL, etc. that do not relate directly to Drupal are off-topic here, but can be asked on Stack Overflow." – Kevin, Pierre.Vriens, leymannx, mradcliffe, sanzante
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Nope, this is pretty much on topic cuz it comes from Drupal core. And handleFragmentLinkClickOrHashChange (form.js?v=8.5.11:137) i still an issue if you are doing a JS app that relies on hashchange for nav. – Nookeen Mar 2 at 1:54
0

handleFragmentLinkClickOrHashChange is a function defined in the Drupal script form.js which attempts to scroll to the corresponding element when the hash (anchor tag) changes, mimicking browser behavior when the anchor tag is changed through visiting a link.

I know it's common to (ab)use the anchor tag like this in Angular and other frameworks but looks like you are going to struggle if you try to combine it with a regular Drupal frontend.

1

Thanks to @Alfred Armstrong pointing down form.js. It seems this event is responsible of that behaviour:

 $(window).on('hashchange.form-fragment', debouncedHandleFragmentLinkClickOrHashChange);

It looks like unbinding it in my custom .js does the trick. We won't benefit from the scroll functionality form.js provides, but we could recreate it with:

$(window).off('hashchange.form-fragment').on('hashchange', function() {
    //something that scroll 
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.