Your problem is that you're attaching the click handler to the document
then trying to remove it from this
which isn't the document
, it's the clicked a
tag. From what I understand you need to remove the click handler on document
and not from this
. But I really do think you're going way over board with this and it could be simple to just have two handlers and swap the class out.
prevent click event on toggleClass
-
04-06-2022 - |
Question
I have a click event on an "a" element:
<a href="#" class="edit-row">Edit</a>
I've attached a click event to this element:
$(document).on('click', "a.edit-row", editRow);
When clicking the edit button the editRow function is called. This function changes the Edit < a > element:
$(this).find("a.edit-row").html("Save").removeClass("edit-row").addClass("save-row").off('click').click(saveRow);
This all works fine.
When clicking on "Save" the saveRow function is called. Within this function I want to revert back to the "Edit" button.
This is one of the versions I've used to achieve this:
$(this).off('click').html("Edit").toggleClass("save-row").toggleClass("edit-row");
I've tried several things other things as well. But what happens, after clicking save it changes to edit but it immediately it changes back to save again.
It looks like the click event from the $(document) part is triggered. However, I can't seem to disable or prevent this click event from triggering when changing the class. It needs to fire once it's clicked again, not on toggleClass().
What am I missing here?
Solution 2
OTHER TIPS
I think you are over complicating things. It looks like all you need is two separate handlers, one for edit-row
and one for save-row
. You shouldn't have to remove click handlers at all.
$(document).on('click','a.edit-row', function() {
$(this).toggleClass('edit-row save-row').html('Save');
//do other stuff in your editRow function
});
$(document).on('click','a.save-row', function() {
$(this).toggleClass('edit-row save-row').html('Edit');
//do other stuff in your saveRow function
});
You can see an example in the fiddle here. http://jsfiddle.net/cc9he/
You could use delegation using the class names to figure out which function to call.
$(function() {
$(document).on('click', "a.edit-row", editRow);
$(document).on('click', "a.save-row", saveRow);
});
function editRow() {
$(this).html("Save").removeClass("edit-row").addClass("save-row");
}
function saveRow() {
$(this).html("Edit").removeClass("save-row").addClass("edit-row");
}