Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

click and re-click function within click function

I have a image in which I wanted to call click and re-click function. So I used .toggle() function instead of .click() function but its hiding the image without click so I decided to make click and re-click function within .click() function like below:

$('.imgclass').click(function(){
   $(this).addClass('btn');
    if($(this).attr('class','btn')){

        $(this).css('background-color','blue');
        $(this).removeClass('btn');
    } else {
        alert('sorry');
    }
});

But in my code else statement is not working. In the first click it add background-color to blue and remove its class and then it wouldn't find the class btn so it should alert 'sorry' but its not alerting. I think there is other best idea to make click and re-click function within .click() function. How to accomplish this?

demo

Upvotes: 1

Views: 2062

Answers (4)

netchkin
netchkin

Reputation: 1384

this happens because after you click the button, you

  1. Add class btn (always)
  2. ask if there is btn class
  3. always find out that there is btn class (because you added it immediately after click in step 1).

Edit: I suggest you moving the addClass into the else block.

Upvotes: 2

Alvaro
Alvaro

Reputation: 41605

Your if condition is wrong.

In order to check whether an element has a class or not you should make use of hasClass function:

 if($(this).hasClass('btn')){

Othewise you are setting the class attribute and checking if it was set correctly.

Your complete code could look like this:

$('.imgclass').click(function(){
   $(this).addClass('btn');
    if($(this).hasClass('btn')){

        $(this).css('background-color','blue');
        $(this).removeClass('btn');
    } else {
        alert('sorry');
    }
});

Although i would recommend you to make use of toggleClass as other mates have pointed out.

Upvotes: 0

Johan
Johan

Reputation: 35194

$('.imgclass').click(function(){

   $(this).toggleClass('btn');

    if($(this).hasClass('btn')){
        $(this).css('background-color','blue');
    } else {
        alert('sorry');
    }
});

In order to make your if case work, you need to use the getter from attr:

if($(this).attr('class') === 'btn'){

This would only work right of the bat if btn is the only class on the button. I recommend my approach over this, though.

Upvotes: 3

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$('.imgclass').click(function(){
    if($(this).hasClass('btn')){
        $(this).removeClass('btn');
    } else {
        $(this).addClass('btn');
    }
});

Fiddle http://jsfiddle.net/xQNK6/3/

Or simply

$('.imgclass').click(function(){
    $(this).toggleClass('btn');       
});

Fiddle http://jsfiddle.net/xQNK6/6/

Upvotes: 1

Related Questions