user1937021
user1937021

Reputation: 10791

have to click twice for click event to work

I have the following code which animates an element when you click a.discover:

$(document).on('click', 'a.discover', function(e){
            e.preventDefault();
            if(toggleState) {
                $(this).addClass('open');
                $(this).parent().find('p.subtitle').stop(true,true).animate({'marginTop': -471}, 1200, "easeOutQuart" );
            } else {
                $(this).parent().find('p.subtitle').stop(true,true).animate({'marginTop': 21}, 1200, "easeOutQuart" );  
                $(this).removeClass('open');
            }
            toggleState = !toggleState;
        });

HTML

<div class="container">
    <p class="subtitle">Released on July 2013</p>
    <a href="" class="discover">Discover Now</a>

    <p class="subtitle">Released on July 2013</p>
    <a href="" class="discover">Discover Now</a>

    <p class="subtitle">Released on July 2013</p>
    <a href="" class="discover">Discover Now</a>
</div>

CSS

.container a.discover{
    z-index: 100;
    display:block;
    position:absolute;
    width:100%;
    color:#fff; 
    text-decoration:none;
    text-transform:uppercase;
    bottom:0px;
    text-align:center;
    font-size:11px;
    font-family:  'univers_55regular', arial,helvetica,clean,sans-serif;
    padding-top:6px;
    padding-bottom:6px;
    background: url("../img/cross.png") no-repeat scroll 73px 7px #000;
}

 .container p.subtitle{
    font-family: 'univers_45_lightregular', arial,helvetica,clean,sans-serif;
    font-size:12px;
    color:#000;
    margin-top:21px;
}   

.container{
    width:930px;
    margin-left:35px;
    }

I have 3 of these buttons so when you click one to animate it, then you need to click the other one twice before it works. An idea what might be wrong? Thanks!

Upvotes: 0

Views: 548

Answers (1)

Romain Meresse
Romain Meresse

Reputation: 3044

You seem to be using a global variable "toggleState", which is shared by every link.

You can use your 'open' class to retrieve state information for the current link :

$(document).on('click', 'a.discover', function(e){
            e.preventDefault();
            if($(this).hasClass('open')) {
                $(this).parent().find('p.subtitle').stop(true,true).animate({'marginTop': 21}, 1200, "easeOutQuart" );  
                $(this).removeClass('open');
            } else {
                $(this).addClass('open');
                $(this).parent().find('p.subtitle').stop(true,true).animate({'marginTop': -471}, 1200, "easeOutQuart" );
            }
        });

Upvotes: 2

Related Questions