I have an application which using dynamic page loading. Everything works fine, but I need to use special javascript code for some specific sections. So it's useless include these js files into the header. So my response contains some html code and js include
I declared for example action for "click" event (toggling image of checkbox) on my application section "todo", when I opened this section and clicked on element which have defined click event, checkbox successfully toggling the image. But when I loaded another section and return back to this "todo" section, after the same click toggling function run twice. When I repeat this process again, toggling function run three times.
Can somebody help me how to avoid this?
Sorry, here's example of my click event code:
$('#container').on('click','.todo-list .todo-done',function(){
var state = '';
if(currentTODO.find('.todo-done').hasClass('fa-square')) {
state = 0;
} else {
state = 1;
}
//return false;
$.post(todoUrl + 'index/toggle_active/',{'id':currentTODO.data('id'), 'state':state},function(){
if(currentTODO.find('.todo-done').hasClass('fa-check-square')) {
currentTODO.removeClass('done');
currentTODO.find('.todo-done').removeClass('fa-check-square').addClass('fa-square');
} else {
currentTODO.addClass('done');
currentTODO.find('.todo-done').removeClass('fa-square').addClass('fa-check-square');
}
});
});
And there's example of my response:
<div class="content">
<script src="todo.js" type="text/javascript"></script>
<div class="col-md-8">
<i class="fa fa-check-square todo-done"></i>
<div class="text">
<div class="text-text">TODO item</div>
<div class="link">
<div class="link-text"><a href="" target="_blank"></a></div>
</div>
</div>
</div>
It's possible to use unbind function before declaration of 'click' event. More here: http://api.jquery.com/unbind/