1

Okay so I have a headache trying to figure this one out. I am working in Drupal 7 with the Omega theme. Trying to get a js file to work.

I have a js file that is set up through the .info file and is showing in view source. The file contents are below. I can get this to work when I place in the wysiwyg on the page however it won't work when I set it up properly as a .js file.

 (function ($) {  
// All your code here
  $('#block-menu-menu ul.menu').removeClass('menu').addClass('sub-menu');

// Create the dropdown base
  $("<select />").appendTo(".menu");

  // Create default option "Go to..."
  $("<option />", {
     "selected": "selected",
     "value"   : "",
     "text"    : "Go to..."
  }).appendTo(".menu select");

  // Populate dropdown with  items
  $(".menu a").each(function() {
   var el = $(this);
   $("<option />", {
       "value"   : el.attr("href"),
       "text"    : el.text()
   }).appendTo(".menu select");
  });

  $(".menu select").change(function() {
    window.location = $(this).find("option:selected").val();
  });

})(jQuery);

My issue is it works when placed in the page, but when I place in the .js file and call it through .info it won't work. Again the file shows up in the view source so it is there. I have to be missing something. NOTE * I am not a developer.

Any thoughts? Thank you!

2

You need to wrap your javascript in a Drupal Behaviors handler. You can read the Javascript Documentation for more information (scroll down and look for the heading "Behaviors").

Basically, your code will end up looking something like this:

    (function ($) {  

      Drupal.behaviors.exampleBehavior = {
        attach: function (context, settings) {            
         // All your code here
       }
     };

   })(jQuery);

If this does not solve your issue, you use check your site for any javascript error messages and update your original post to include them. The way I recommend to do this is to install the Web Developer plugin for Firefox and open up the Error Console (tools -> web developer -> error console) and look for messages highlighted in red.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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