Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    May 2010
    Posts
    308
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Jquery remove change class question

    I have this code.
    Code:
    <script>
    $(document).ready(function(){
    	
    $("#click").attr('class', 'xxx');
    
    	 $("#next").click(function(){
    		
    		$('#click').addClass('ppp').removeClass('xxx');
        });
    	
    	 $(".xxx").click(function(){
            alert("The paragraph was clicked.");
    		
        });
    });
    </script>
    Code:
    <p id="click"> Click on this paragraph.</p>
    <p id="next"> Change class</p>
    If i click change class, i want it to change the class name to ppp. But why is that after clicking Change class, the alert message still shows after clicking Click on this paragraph? How can I work this properly?
    Last edited by Anishgiri; 01-10-2017 at 05:18 AM.

  2. #2
    Master Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    5,161
    Thanks
    19
    Thanked 543 Times in 537 Posts
    But why is that after clicking Change class, the alert message still shows after clicking Click on this paragraph?
    because the event handler is attached to an element. you use the change class to select the elements that get the handler added. then removing that class does not remove the handler.

    if you want the event to be depending on a class, use event delegetion:
    Code:
    $(document).on('click', '.xxx', handler);
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •