Charbel Wakim
Charbel Wakim

Reputation: 146

addClass removeClass bugs jQuery

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.

Upvotes: 0

Views: 265

Answers (4)

Parker Selbert
Parker Selbert

Reputation: 1546

By using the 'click' event you don't have a persistent selector, so when you remove the video-left class without rebinding it will no longer handle the event.

$('.video-left').on('click', function(event) {
  $('.video-middle').addClass('video-left').removeClass('video-middle')
  $(this).addClass('video-middle').removeClass('video-left')
})


$('.video-middle').on('click', function(){ alert('middle'); })

Upvotes: 0

walmik
walmik

Reputation: 1452

Add the class video-left to both the elements and add the class 'video-middle' (along with 'video-left' to the element you want 'video-middle' to be by default.

<div class='video-left'></div>
<div class='video-left video-middle'></div> <!--default video middle -->

Then

$('.video-left').click(function(){
    $('.video-middle').removeClass('video-middle');
    $(this).addClass('video-middle');
}

Upvotes: 0

Tigra
Tigra

Reputation: 2631

You doing it wrong

What you do is attaching events to elements, you don't attach elements to classes, as you suppose

And each time when you click on the element, that was .video-left the function that resides in first click() executed. Same one

What you should do, is to add class "video" to all elements and to attach common event

$('.video').click(function(){
if($(this).hasClass('.video-left')) {do_something1();return} 
if($(this).hasClass('.video-middle')) {do_something2();return}
})

Upvotes: 0

JJJ
JJJ

Reputation: 33143

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.

$( document ).on( 'click', '.video-left', function(e) {
   // ...
});

(You could also use any parent of the video elements instead of document, provided that they don't change at any point.)

Upvotes: 4

Related Questions