0

I have custom module called interface, through which I'm adding a javascript file. This code is in plain old javascript, no jQuery, and has been working for me.

I now want to be able to add some jQuery functions to this code, I thought this would be possible since jQuery and javascript should be compatible with each other, right?

So here's a simplified example of what I'm doing inside the .js file:

(function ($) {
    Drupal.behaviors.interface = {
    attach: function()
    {
        function foofunction() {
        // execute some code
        }
    function WelcomeScreen()
    {
        Screen.apply( this );
        this.html = function(){
        return "<p></p>";
        };
this.activate = function(){
document.getElementById("main").innerHTML = "<a id=\"button\" onClick\"foofunction()\">Test</a>";
        };
        }

    }
    }
})(jQuery)

This code results in the following error in Chrome dev tools:

Uncaught ReferenceError: foofunction is not defined 

My guess is that somehow the required jquery wrapper or the drupal behaviors wrapper are causing the functions to no longer be 'global'.

One obvious answer, I think, is rewriting everything in proper jQuery syntax. But I'm interested in how to make these javascript functions compatible with jQuery.

1 Answer 1

1

"Drupal way " is to attach events in behaviors. This is the code I use without problems.

(function($) { 
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      
      function test(param) {
        alert($(param).attr('token'));
      }
      
      $(':input', context).on('keyup change', function(){
        test(this);
      });
    }
  };
})(jQuery);

Alternatively, this code is shorter.

(function($) { 
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      
      function test() {
        alert($(this).attr('token'));
      }
      
      $(':input', context).on('keyup change', test);
    }
  };
})(jQuery);

Rewrite your code to that syntax, make sure you are using jQuery Update, and you should be good.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.