I am trying to write a jQuery code that simply switches classes on click, so i have two elements one with a class video-left the other video middle, and on click they switch classes, this is working in fire bug the classes switch and also their positions (which are related to classes), but when i click a second time the jQuery acts as if the classes did not change …
followig is the code:
$('.video-left').click(function(){
$('.video-middle').addClass('video-left');
$('.video-middle').removeClass('video-middle');
$(this).addClass('video-middle');
$(this).removeClass('video-left');
});
$('.video-middle').click(function(){alert('middle');});
so if i click left first then what is now left it triggers the alert.
When you do something like
$( '.video-left' ).click()the click event is attached to the element, not to the class. That is, if the element’s class changes, the click event doesn’t change because the event is attached to the element itself.In this case when you want to attach the event to a class you should use
.on()that has the selector checked individually every time the user clicks on the element.(You could also use any parent of the video elements instead of
document, provided that they don’t change at any point.)