Justin Lachapelle Justin Lachapelle - 1 year ago 54
HTML Question

Html update on Jquery click event

I have a tabbed DIV element that changes on first click but after that loses functionality

HTML:

<div id="holder">
<ul style="list-style:none; margin:0; padding:0;">
<li><a name="CondLink"id="onlink">Link1</a></li>
<li><a name="EffLink">Link2</a></li>
</ul>
</div>


Javascript(Jquery):

$('a[name=CondLink]').click(function(){
$('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink" id="onlink">Link1</a></li><li><a name="EffLink">Link2</a></li></ul>');
});

$('a[name=EffLink]').click(function(){
$('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink">Link1</a></li><li><a name="EffLink" id="onlink">Link2</a></li></ul>');
});


Clicking either tab properly updates the HTML on the first click only but does does not execute either function on any followup clicks.

(NOTE: The console does not give me any errors but also does not hit a breakpoint inside either of the click functions on followup clicks)

Answer Source

That's because you're replacing your links. So the bound event listeners are no longer on the new links, so just rebind them after replacing the links.

function bindClicks(){
  $('a[name=CondLink]').click(function(){
    $('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink" id="onlink">Link1</a></li><li><a name="EffLink">Link2</a></li></ul>');
    bindClicks();
  });
  $('a[name=EffLink]').click(function(){
    $('div[id=holder]').html('<ul style="list-style:none; margin:0; padding:0;"><li><a name="CondLink">Link1</a></li><li><a name="EffLink" id="onlink">Link2</a></li></ul>');
    bindClicks();
  });
}
bindClicks();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="holder">
<ul style="list-style:none; margin:0; padding:0;">
<li><a name="CondLink"id="onlink">Link1</a></li>
<li><a name="EffLink">Link2</a></li>
</ul>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download