4

I have this code that does not work. I know why it does not work - first time page is loaded 'context' is all page and jquery easely finds '.view-SPECIFICVIEW .view-content'. After AJAX 'context' has changed and it is now just '.view-SPECIFICVIEW' and inside that there is no class '.view-SPECIFICVIEW' and therefore nothing happens. Script works if I remove '.view-SPECIFICVIEW' from find(), but then all views are selected.

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $(context).find('.view-SPECIFICVIEW .view-content').masonry({
          columnWidth : 300,
          gutterWidth : 20
        });
      }
    }
})(jQuery, Drupal, this, this.document);

I would like to have this code to work with '.view-SPECIFICVIEW' and also I would like to know how code changes if multiple, different specific views should be targeted.

3
+100

Just stop using context in this case. I've been playing around with jQuery Masonry and I've not needed to use it.

(function ($){
  Drupal.behaviors.myModule ={
    attach: function(context, settings) {
      $('.view-SPECIFICVIEW .view-content').masonry({
        columnWidth : 300,
        gutterWidth : 20      
      })    
    }
  }
})(jQuery);

FYI, I'd also take a look at the Masonry recommendation to use the imagesLoaded plugin if there are images in your view. It takes a LOT of future frustration out.

  • You mean I should use attach as attach: function() without context and settings? Masonry is absolutely not important in this case. – henrijs Jun 14 '12 at 10:11
  • You can pass context and settings through, but if you're not using them there seems little point. I'm just saying, rather than use $(context).find just use $('.view-SPECIFICVIEW .view-content') – Chapabu Jun 14 '12 at 10:30
  • .find() is also an extra function call, so I'd imagine it's slightly slower. It's probably negligible though. – Chapabu Jun 14 '12 at 10:31
  • Ok, tested. Thanks. "Just stop using context" appears to be correct answer. – henrijs Jun 19 '12 at 20:09
0

Give this a try, Context acts as "live" so doing it this way will attach it to each instance of view-SPECIFICVIEW (this is if I understand what your asking)

(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.MYMODULE = {
      attach: function(context, settings) {
        $('.view-content',context).each(function(){
         /* ADD CODE HERE */
        });
      }
    }
})(jQuery, Drupal, this, this.document);
  • Main problem is that there is no .view-SPECIFICVIEW in context after AJAX. context IS .view-SPECIFICVIEW. Im still waiting for a chance of real world test, any hour now. – henrijs Jun 18 '12 at 2:37

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.