简体   繁体   中英

jQuery click event needs 2 clicks in second bind event to fire

I am tring to fire 2 events on a single click.

Please see this JSFIDDLE . The user should be able to click repeatedly to get the arrow to spin round, and the div to move over, and then move back.

The first bind event works fine and the arrow spins round, but the div wont start moving over until the second click.

HTML

<div class="arrow">
            <img src="http://www.avenir-telecom.co.uk/common_files/images/right-arrow.png" alt="Click here to show contracts" id="arrow"/>
</div>
<div id="page">
    <h1>Some Heading Here</h1>
    <p>This is some text to make the div look normal</p>
</div>

CSS

.arrow
{
    float: left;
}
#page
{
    width: 400px;
    position:relative;
    background-color: #1371BE;
    padding: 10px;
    margin-left: 35px;

}

jQuery

$(function ($) {
    var value = 0;
    $('img#arrow')
    .bind('click',function(event){
       value += 180; 
       $(this).rotate({animateTo:value}, 300);
    })
    .bind('click',function(event){
        var x = $(this).data('open');
        $('#page').animate({
            left: (x) ? '100px' : '0',
            load: true
        }, 300);
        x ? $(this).data('open', false) : $(this).data('open', true);
    });

}); 

It must be something simple!

You just need to verify if x is undefined and if so, set it true .

if (x === undefined) x = true;

JFIDDLE

Is this what you are looking for?

    $('#page').animate({
        left: (!x) ? '100px' : '0',
        load: true
    }, 300);

http://jsfiddle.net/g2tAN/6/

I combined the 2 binds into 1, there is no point doing 2 different binds. Also added a ! to the left. I think you had it backwards there that's why it was not working properly

Add .data("open", true) so that it is defined.

$('img#arrow').data("open", true)
.bind('click',function(event){
   value += 180; 
   $(this).rotate({animateTo:value}, 300);
})

http://jsfiddle.net/prankol57/ZK6Pd/

Also, your open seems backwards. Shouldn't it open if open was previously set to false?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM