user1625714
user1625714

Reputation: 93

Jquery works only once

The jquery code goes through a nested list. Once it loads, it works well once (switches classes), but a full click through it won't repeat. The class switches a triangle bullet from left facing to downwards. I can't figure how to get it to repeat. Any help much appreciated.

jQuery(document).ready(function() {
  jQuery(".list-year").click(function() {        
    jQuery(this).removeClass('list-year li');
    jQuery(this).addClass('list-year-down li');  
    jQuery('.list-month').toggle( function() {
        jQuery(".list-year-down").click(function() {
            jQuery(this).removeClass('list-year-down li');
            jQuery(this).addClass('list-year li'); 
        });
    });        
  });
});

Upvotes: 0

Views: 784

Answers (5)

D.clixer
D.clixer

Reputation: 91

try :D

jQuery(document).ready(function() {
  jQuery(".list-year").click(function() {        

    jQuery(this).toggleClass('list-year list-year-down');

  });
});

Upvotes: 0

Jai
Jai

Reputation: 74738

try Toggling the class .toggleClass():

jQuery(document).ready(function() {
  jQuery(".list-year").click(function() {        
    jQuery(this).toggleClass('list-year-down');
    jQuery('.list-month').toggle( function(e) {
      e.stopPropagation();
      jQuery(".list-year-down").click(function() {
        jQuery(this).toggleClass('list-year-down'); 
      });
    });        
  });
});

on Default put this class to lis: list-year li

Upvotes: 0

james emanon
james emanon

Reputation: 11807

Because you remove the .class that you put the click handler on, THEN you remove it - you loose that binding. Do what Dipesh above suggests use ".on" for jQuery 1.7 or greater, else you can use ".live" (deprecated).

Upvotes: 0

Anujith
Anujith

Reputation: 9370

Attach an event handler to a parent element using .on(), and pass the selector as an argument.

Try:

jQuery(document).ready(function() {
  jQuery(document).on('click, '.list-year', function() {        
    jQuery(this).removeClass('list-year li');
    jQuery(this).addClass('list-year-down li');  
    jQuery('.list-month').toggle( function() {
        jQuery(".list-year-down").click(function() {
            jQuery(this).removeClass('list-year-down li');
            jQuery(this).addClass('list-year li'); 
        });
    });        
  });
});

Also note that for jQuery 1.9.1 +, toggle() won't work as before...

Upvotes: 1

Dipesh Parmar
Dipesh Parmar

Reputation: 27354

Try

jQuery(".list-year").on('click',(function() {        

Upvotes: 1

Related Questions