1

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

4 Answers 4

3
$('.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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

It's true, on each click, class 'btn' is added, so the condition is always true.
1

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/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.