0

I have the <div id="SocialInteract">

$('#SocialInteract').click(function() {

$('#SocialCount').load('sc.php');
$('#TeacherAttendance').removeAttr('id');
});

When I view the InspectElement the #id is removed but it still takes the click. Something I am doing wrong?

xyz
  • 21,367
  • 33
  • 107
  • 150
X10nD
  • 19,972
  • 44
  • 105
  • 150

5 Answers5

3

Your click event still fires because the event is already attached to the TeacherAttendance element.

If you want to detach the click event, you should use off() or unbind() :

$('#TeacherAttendance').off('click');
$('#TeacherAttendance').unbind('click');
bobthedeveloper
  • 3,627
  • 2
  • 13
  • 30
  • the DOM object of "TeacherAttendance" has attr 'id' no more but the event registered still exists. another way is to have function pointer to the click event you assigned and you have the event object for the DOM "TeacherAttendance" , then you can play with it – harshal Apr 19 '14 at 11:12
2

Removing id wont remove already attached click event. Use unbind() method to remove attached event.

$('#TeacherAttendance').unbind("click");

EDIT :

You should use off() as its the updated one. unbind() is still there for backword compatibility

$('#TeacherAttendance').off('click');

Related question : Best way to remove an event handler in jQuery?

Community
  • 1
  • 1
xyz
  • 21,367
  • 33
  • 107
  • 150
1

You are binding to the DOM element the event, then you remove the id but the event it's already registered.

use off or unbind or set a global var to turnoff/remove/doNothing .

MrPk
  • 2,629
  • 2
  • 18
  • 25
1

.click() just attaches and forgets. It doesn't care whether anything happens to that element.

So you've to manually unbind the event.

.unbind('click');
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
0

To make the event binding dynamic, attack it to the document and wait for it to bubble up:

$(document).on('click', #SocialInteract', function() {

$('#SocialCount').load('sc.php');
$('#TeacherAttendance').removeAttr('id');
});

This way the event is registered to the document node: if the click event was fired on an element that had that ID, it will trigger. If not, it won't.

Barney
  • 15,464
  • 5
  • 56
  • 73