2

I have a Drupal.behaviors.leftmenusticky script that converts a left menu to a sticky menu (100% height,position fixed and the like) but I want to drupal_add_js it only if the menu actually exists in the page shown.

(function ($) {
  if ($(".full-height").length > 0 ) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {    
        var contentHeight = $("#main").innerHeight();
        var viewportHeight = $(window).height();
        var offsetTop = $(".full-height").offset().top;
        if (contentHeight < viewportHeight) {
          jQuery(".full-height").height(viewportHeight-offsetTop);  
        } 
        else {
          jQuery(".full-height").height(contentHeight-offsetTop);
        }
        leftColumnResizer();
        $(window).bind("resize", leftColumnResizer);
        function leftColumnResizer () {
          var toto = $(".region-sidebar-first").width();
          $("#block-paddle-menu-display-management-level-4").css("width", toto);
        }
      }
    }
  }
  else {console.log('notfound');}
})(jQuery);

The Javascript way would be to check whether or not the class I'm targetting exists or not:

  if ($(".full-height").length > 0 )

but 1) I don't know where to place this check exactly and 2) I'd prefer to have a template.php way of doing that by making use either of settings or of context...

Is this possible?

2

drupal_add_js() happens server-side, it can't possibly have exposure to what's in the DOM (unless you pass that info back to the server with AJAX, but that would be a very weird thing to do). The correct solution is the javascript one as you've mentioned.

You want that code to run whenever the DOM is ready, so in the Drupal paradigm immediately inside the attach function of your behaviour:

(function ($) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {    
        if ($(".full-height").length > 0 ) {
          var contentHeight = $("#main").innerHeight();
          // ...

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.