1

I created a tab of buttons using bootstrap .I made them dynamically by using a loop.

<ul class="nav nav-tabs" style="border-bottom:0px">
   <li class="active">
      <a data-toggle="tab" class="mybtn" id=' + mapport.selected_feature_layer[i] + '>' + layer_names[i] + '</a>
   </li>
</ul>

And When I assign them an active class it worked for me .But after I assign them a class and call a function self.click($(this).attr('id')); the class active disappears and the design disappears of the class active.

Why this is happening ?

 $(".mybtn").click(function(){
    self.click($(this).attr('id'));
    $('.active').removeClass('active')
    $(this).addClass('active'); 
});
2
  • what is self.click($(this).attr('id')); include also in OP Commented May 15, 2017 at 8:44
  • @guradio Click is a function to which I am passing Id of currently pressed button. Self is used as I am using this function globally. Commented May 15, 2017 at 8:45

1 Answer 1

1

You need to define the click function in a different way in order to make it work for dynamically added elements

$(document).on("click", ".mybtn", function(){
    //self.click($(this).attr('id'));
    $('.active').removeClass('active')
    $(this).addClass('active'); 
});
.active {background-color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav nav-tabs" style="border-bottom:0px"><li><a data-toggle="tab" class="mybtn" id='abc'>abc</a></li><li><a data-toggle="tab" class="mybtn" id='abc'>abc</a></li></ul>

Sign up to request clarification or add additional context in comments.

3 Comments

I edited the snippet to include a color for the active element and added another <li> element. You had <li> as active, in my code the <a> is active because that is what you click on. Furthermore, the self.click is deactivated.
till here I have done already .I mentioned in question that "When I use "self.click($(this).attr('id'));" then problem occur. Without using this its working fine. I need solution If I can use both (function call and active class) in a same function or anyother soloution
thank you I was call from 2 functions that's why overwriting was happening.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.