Hai,

i am using drupal 7

we need to active menu onclick so i am write given below code in separate file.js
it will work only on loading time after loaded it does not working

when click third a[tag] added class active example[a hrfe="#" class="active"] after load finish [a hrfe="#"] active removed

anything write code it's only working load time.

(function ($) {
Drupal.behaviors.mybehavior = {
attach: function (context, settings) {

$(document).ready(function(){
$(".nav-collapse ul li:nth-child(3) a").click(function(){
$(".nav-collapse ul li:nth-child(3) a").addClass("active");

});
});

}}
})(jQuery);

Thanks&Regards,
J.Jayaprakash

Comments

Jaypan’s picture

Don't use $(document).ready(). That's an onload function, and Drupal.behaviors is an onload function, so they conflict.

Also, you should use $.once() before adding any handlers, or else they will be added multiple times.

You want this:

(function ($) {
  function navClickWatcher() {
    $(".nav-collapse ul li:nth-child(3) a").once("nav-click-watcher", function() {
      $(this).click(function() {
        $(".nav-collapse ul li:nth-child(3) a").addClass("active");
      });
    });
  }

  Drupal.behaviors.mybehavior = {
    attach:function() {
      navClickWatcher()
    }
  };
}(jQuery));
prakash.j’s picture

thanks for your quick reply

it is working after load but

i need to add class on click the a tag. for ex. first i click on first a tag need to add the active class and then i need to navigate to another a tag it will add to that a tag only. not previous tag.

Its a menu function active class.

we need only particular a[tag] click when add class

Thanks&Regards,
J.Jayaprakash

Jaypan’s picture

You can do whatever you need to do inside the .click() function. Just replace the following code with whatever you need:

$(".nav-collapse ul li:nth-child(3) a").addClass("active");
prakash.j’s picture

thank you so much
i need current page active script

when u click any menu page it will be add active class in a [tag]

Thanks&regards
J.Jayaprakash

Jaypan’s picture

I'm happy to give support on how to use Drupal's JavaScript API, but you are now asking questions about how to write jQuery. You should ask those questions on a jQuery forum.

VM’s picture

per: https://www.drupal.org/node/643758 please edit the opening post and move it to the 'post installation' forum.

Thank you.