1

I have a drupal 7 site and I'm loading a theme level jquery script by adding this in my .info file:

scripts[] = script.js

I want it to move an views ajax pager every-time a link is clicked (link changes vote on content like on hotornot.com). Exact code I'm using in my script.js is below and so far it's working, but it only works on the first click and not afterwards. How can I have this $("li.pager-next a").click(); happen on EVERY click of a.ratebutton?

(function($) {
  $(document).ready(function() {        
     $("a.rate-button").click(function(){

    // $(this).hide();
    $("li.pager-next a").click();
      // window.location = $("li.pager-next a").attr('href');

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

2 Answers 2

3

You should use Drupal's JavaScript behavior system and jQuery Once instead of document ready. Other well behaving code adding content to the page should then attach all defined behaviors using Drupal.attachBehaviors(addedElement).

(function($) {
  Drupal.behaviors.myFunkyTheme = {   
    'attach': function(context, settings) {
      $("a.rate-button", context).once('funky-theme').click(function(){
        // $(this).hide();
         $("li.pager-next a").click();
         // window.location = $("li.pager-next a").attr('href');
      });
    }
  }
}(jQuery));
2
  • THANKS! This worked very well, and I've selected it as the best answer. my question to you is why do you need the .once? It does fire EVERY time I click the link, which is EXACTLY how I wanted it to behave, but that seems counter-intuitive to the .once. am I missing something? Using this example, how could it be modified to run only once? Commented Nov 30, 2011 at 17:22
  • Behaviors are attached to updated DOM element (the context parameter). But code updating the DOM is not required to use the narrower element. Something the behaviors are attached to an element containing already processed elements. The use of .once() prevents the the click handler to be registered multiple time on the same element (ie. a.rate-button). Commented Nov 30, 2011 at 18:14
0

I'm not sure if this is your case, but if the link is rebuilt by ajax you must use live() (if you are using jQuery prior to 1.7)

 $("a.rate-button").live('click', function(){

// $(this).hide();
   $("li.pager-next a").click();
  // window.location = $("li.pager-next a").attr('href');

   });

or on() jQuery 1.7 and after

$("body").on("click", "a.rate-button", function(){
   $("li.pager-next a").click();
});
0

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.