0

I have added a custom jQuery file to my theme with the theme.libraries.yml. In my laptop and fullscreen browsers the added javascript is working without any issues. But it seems the javascript does not have any effect in mobile browsers(I'm testing with ipad and iphone browsers in both safari and chrome). My custom_theme_libraries.yml is as following

global-scripts:
  js:
  js/jqueryfile1.js: {}
dependencies:
- core/jquery

And my jqueryfile1.js is as following

(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

Is there any additional configurations to be considered to get the code works in mobile browser also?

4
  • No - JavaScript is JavaScript, if the file is in the source then the code will be executed, there's no mobile v non-mobile distinction unless your JS code checks the viewport/user agent. You can easily tell by adding test code, e.g. an alert, at the top of the file. By the by, the use of ready is redundant, behaviours are already delayed until DOM ready
    – Clive
    Commented Apr 29, 2017 at 12:36
  • Yes, the difference is not mobile, probably logged in or not. The error could be the missing spaces before the dependencies in the yaml file.
    – 4uk4
    Commented Apr 29, 2017 at 12:43
  • Thanks i will take these into consideration and and will update you the result soon Commented Apr 29, 2017 at 13:08
  • You don't need to add document ready, that is redundant within a behavior.
    – Kevin
    Commented Apr 29, 2017 at 13:28

1 Answer 1

3

It seems like your code is the problem. You have extra });

Should be

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      $(document).ready(function() {
        // code goes here
      });
    }
  };
})(jQuery);

But it is nonsense to use $(document).ready as it is already handled by Drupal.behaviors.

So the proper way is.

(function ($) {
  Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
      // code goes here
    }
  };
})(jQuery);

The attach() method is called when the DOM has loaded both initially and after any AJAX calls.

See this doc for more info. https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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