Wojciech Zieliński
Wojciech Zieliński

Reputation: 77

What am I doing wrong with this simple click function?

I want to make simple jQuery script. I have two divs. First is called 'but' and second is called 'tun'. What I want to do is when you click but -> tun hides and but has new class active. When you click on active tun shows and class active is removed. So it's kinda like toggle but I really don't want to use toggle becouse I need different actions on first and second click.

Here is my code:

$('.but').click(function(){
    $(this).addClass('active');
    $('.tun').hide('slow');
});
$('.active').click(function(){
    $('.tun').show('slow');
    $(this).removeClass('active');
});]

Why it is not working ?

http://jsfiddle.net/wcwny064/

Upvotes: 1

Views: 57

Answers (3)

kalkanbatuhan
kalkanbatuhan

Reputation: 178

or you can do it like this

$('.but').click(function(){
    if($(this).hasClass("active"))
    {   
      $('.visible').show('slow');
      $(this).removeClass('active');        
    }
    else
    {
      $(this).addClass('active');
      $('.visible').hide('slow');
    }
});

Upvotes: 1

Emre Erkan
Emre Erkan

Reputation: 8482

Instead of using .click() function directly attach to document's click event with a selector like this;

$(document).on('click', '.but', function(){
    $(this).addClass('active');
    $('.visible').hide('slow');
}).on('click', '.active', function(){
    $('.visible').show('slow');
    $(this).removeClass('active');
});

This way you delegate the event to document. At a t moment when click event occurs if document has element which matchs your selector, your function will run.

In your code, when you use .active selector and bind click event, there is no element with active class. Therefor you can't bind second click event.

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74410

You are binding event to specific elements, there is no on-the-fly processing regarding selector later. You can just delegate event. That's said, you could use following logic instead:

$(document).on('click', '.active, .but', function(){
    $('.visible').stop().toggle('slow'); // stop() to handle multiple clicks
    $(this).toggleClass('active but');
});

-jsFiddle-

Upvotes: 2

Related Questions