0

I'm trying to add and remove the class on click event. I'm adding and removing the three classes onclick event of .the-old, its working properly.

Onclick Event (.the-old)

  1. add class on button tag (.the-new)
  2. Add and remove class on ids #navbar-hamburger-01 and #navbar-closed

JS

$(function() {

  $('.the-old').on('click',  function() {
        //alert('..');
     $('#navButtonToggle').addClass('the-new');
     $('#navButtonToggle').removeClass('the-old');
       $('#navbar-hamburger-01').addClass('hidden');
       $('#navbar-closed').removeClass('hidden');    
    });

    $('.the-new').on('click',  function() {
        alert('..');

       $('#navbar-hamburger-01').removeClass('hidden');
       $('#navbar-closed').addClass('hidden');    
    });

});

HTML

<button id="navButtonToggle" type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle repnsive-navbar-toggle the-old">
    <div id="navbar-hamburger-01">
    <span class="sr-only">Toggle navigation</span>

    <span class="icon-bar"></span>

    <span class="icon-bar"></span>

    <span class="icon-bar"></span>
    </div>
    <div id="navbar-closed" class="hidden">
    <span class="glyphicon glyphicon-remove"></span>
    </div>
</button>

But this function does not working $('.the-new').on('click', function() {}), even i just try to alert, but it does not working. However class .the-new is properly adding onclick event of the-old. Can any guide me where i'm wrong.

Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68
  • 1
    Possible duplicate of [JQuery Click event not working after adding class using JQuery](http://stackoverflow.com/questions/16893043/jquery-click-event-not-working-after-adding-class-using-jquery) and several others – JJJ Jan 31 '16 at 14:07
  • 1
    Use jquery event delegation `$("parent").on('click', "delegatedItem", function() {\\ actions})`; – Bourbia Brahim Jan 31 '16 at 14:09
  • 1
    Events are binded when JavaScript is executed initially. In later phase of execution cycle of your program, classes are changed hence events on those elements are not attached at all.. – Rayon Jan 31 '16 at 14:10
  • @RayonDabre Ok, so second function does not working due to the changed of classes. Is there other way handle event of `.the-new` – Ayaz Ali Shah Jan 31 '16 at 14:15
  • may be You are creating element on fly, and thats why on event isnt working. You should attach on event to element created before. – Vasim Shaikh Jan 31 '16 at 14:15
  • 1
    You must read about event delegation in which events are attached to parent elements which are not changed during execution. Try this: `$('body').on('click', '.the-new', function() { });` – Rayon Jan 31 '16 at 14:18
  • `$(".blah")` in jQuery means: return a list of elements with the `blah` class that are on the page *right now* - when the code executes. The methods called on that list can only operate on its contents. – millimoose Jan 31 '16 at 14:18
  • @Rayon - for performance reasons it's usually better to set up a delegated event on the "static" parent that's closest to the "dynamic" elements in the hierarchy. Intercepting events on `` means jQuery has to inspect every single event that happens whose propagation isn't stopped. – millimoose Jan 31 '16 at 14:21
  • @millimoose, Totally agree with you, I have mentioned the same in the comment. I am unable to guess `static parent` in the provided markup hence I chose `body` – Rayon Jan 31 '16 at 14:23

2 Answers2

0

The reason for this already explained in previous answer. To make it work you can integrate either of these changes

    <button id="navButtonToggle" type="button" data-target="#navbarCollapse" data-toggle="collapse" class="navbar-toggle repnsive-navbar-toggle the-old">
        <div id="navbar-hamburger-01">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        </div>
        <div id="navbar-closed" class="hidden">
        <span class="glyphicon glyphicon-remove"></span>
        </div>
    </button>
<script>
  $(function() {
          $('.the-old').on('click',  function() {
                //alert('..');
             $('#navButtonToggle').addClass('the-new');
             $('#navButtonToggle').removeClass('the-old');
               $('#navbar-hamburger-01').addClass('hidden');
               $('#navbar-closed').removeClass('hidden');    
            });
           $('.the-new').on('click',  function() {
                alert('..');
            $('#navbar-hamburger-01').removeClass('hidden');
               $('#navbar-closed').addClass('hidden');    
            });
       });
    </script>

OR

delegate the event without making any changed to HTML

$(function() {

  $('body').on('click','.the-old', function() {
        //alert('..');
     $('#navButtonToggle').addClass('the-new');
     $('#navButtonToggle').removeClass('the-old');
       $('#navbar-hamburger-01').addClass('hidden');
       $('#navbar-closed').removeClass('hidden');    
    });

    $('body').on('click','.the-new'function() {
        alert('..');

       $('#navbar-hamburger-01').removeClass('hidden');
       $('#navbar-closed').addClass('hidden');    
    });

});
brk
  • 48,835
  • 10
  • 56
  • 78
  • please consider accepting & upvoting the answer for future reference – brk Jan 31 '16 at 14:21
  • If reason and explanation in provided in previous answer then that should be accepted over this right ? – Rayon Jan 31 '16 at 14:24
  • @RayonDabre seems you got it wrong the previous answer only explain it but does not give a solution – brk Jan 31 '16 at 14:27
  • Your answer is incomplete too...It provides only solution without explanation. – Rayon Jan 31 '16 at 14:34
  • @RayonDabre that is why I asked to refer to previous answer for reason and explanation ... and I also wrote you got it wrong.By the way SO is not for pointing personal mistakes. If you are unhappy with answer down vote it citing proper reason.I will bring that in notice to moderators – brk Jan 31 '16 at 14:38
  • 1
    What if he deletes the answer ? There is no point referring others description..you must mention your own..answer without explanation is not gonna help future users... – Rayon Jan 31 '16 at 14:47
-3

When you register the event handlers for click, the class the-new does not exist so when you actually register it nothing happens.

You need to register it inside the handler of add-new. This is however risky because you need to "de-register" it once the-new is removed or else you will: 1) Have duplicate handlers that grow on every click. 2) Handle the-XXX event even if its not logically what you meant.

I would suggest creating a common base css class for the element and working on it, checking what is the state, then adding the right class accordingly. You already do it when you register the 1st handler via element ID.

Also note that in the callback you don't need to do a DOM query for the element, you can get it from the $event parameter supplied when the handler gets invoked.

See the jQuery docs for that.

Shlomi Assaf
  • 2,178
  • 18
  • 19
  • No, a race condition is when the behaviour of concurrent code is unpredictable, because two or more events can happen in arbitrary order. (I.e. there is a "race" to see which one happens first.). The rest of the answer doesn't fare much better, this sort of schematic suggestion belongs in comments, if anywhere. If the OP's question doesn't allow for a "hood" answer because it's missing details, it should be improved first. – millimoose Jan 31 '16 at 21:19