0

I got a div with a default class of 'unlock' and text named 'UNLOCK'. when i click it, it says 'UNLOCK' and at the same time remove the class 'unlock' and add a class of 'lock'.

html

<div class='unlock'>UNLOCKED</div>

this worked

$('.unlock').click(function(){
    $(this).removeClass('unlock').addClass('lock').text('LOCKED');
});

but this did not worked

$('.lock').click(function(){
   $(this).removeClass('lock');
});

And I'm not sure why it didn't work coz the class was already replaced so it should work right?

Basically, all I want is like a toggle functionality that when you first click it should say LOCKED. then when you click it again, it should say UNLOCKED.

I tried the toggle() but it didn't work also or I just don't know how to implement it. So any ideas how I can make this functionality work?

here's the fiddle

anagnam
  • 143
  • 1
  • 9

1 Answers1

2

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call. So, $('.lock') doesn't exists when event binding is performed thus event handler is not binded.

You need to use Event Delegation using .on() delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Example

$(document).on('click', ".lock", function(){
    $(this).removeClass('lock');
});
Satpal
  • 132,252
  • 13
  • 159
  • 168