Reputation: 3871
I have read couple of others questions like this, but they are basically using deprecated .toggle()
function.
I'm struggling to achieve that div#p
on first click goes right and on second click goes back to starting position.
I wrote this code:
$(function(){
$("#p").on("click", function(){
if ($("#p").data("right") == 'n') {
$("#p").animate({marginLeft:"50"}, 500);
$("#p").data("right", 'y');
} else {
$("#p").animate({marginLeft:"0"}, 500);
$("#p").data("right", 'n');
}
})
})
which is working with one big error: after page is loaded, first click fires nothing.(second and other clicks are switching animation action correctly).
What's the catch here, how to correct this?
Upvotes: 0
Views: 822
Reputation: 319
I wrote similar code with ideas from this thread. This is for 1 div but it can be rewrite to tag "p" as you used in this thread.
$( ".content" ).click(function() {
if( $( this ).hasClass( "vysun" ) ){
var status = true;
$( this ).removeClass( "vysun" );
}
else{
var status = false;
$( this ).addClass( "vysun" );
}
$( this ).animate({width : status ? "33%" : "100px"}, 1500, "linear");
});
Upvotes: 0
Reputation: 318302
$(function(){
$("#p").on("click", function(){
var state = parseInt( $(this).css('margin-left'), 10 ) > 0;
$(this).animate({marginLeft : state ? 0 : 50}, 500);
});
});
or with data, and accounting for undefined data values :
$(function(){
$("#p").on("click", function(){
var state = $(this).data("right");
$(this).animate({marginLeft: (state ? 50 : 0)}, 500);
$(this).data("right", !state);
});
});
Upvotes: 2
Reputation: 868
You're trying to fetch data-right
but I don't think you have set that already. You should set it upon loading of your page so you can actually retrieve it. Either use .ready()
or just add data-right
to your <p>
Upvotes: 1