Reputation: 531
I've the following function:
$('.link1').click(function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
It toggles a div and scroll the page down. The problem is that everytime the user toggles the page scroll down again...how could I run this animate function only at first click?
Upvotes: 6
Views: 20361
Reputation: 1
The following works with JQuery.
The CSS used:
.cpos {
position: relative;
top: -1.65em;
left: 1.8em;
}
The JQuery used:
var p=null; /* Initialize variable p. */
p=$("b").detach(); /* Detach every possible <b>b</b>-tags. */
var p=$("<b>Console loaded!</b>").addClass("cpos"); /* Do anything, like adding class. */
p.appendTo("#container"); /* Append new data to the anchor container. */
Maybe you could use this for reference when animating. ;)
Upvotes: 0
Reputation: 341
This should do it
(function(){
var first=true;
$('.link1').click(function(){
if (first){
first=false;
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
}
});
})();
Upvotes: -1
Reputation: 2108
You can save a simple "token" to check if is the first time that click is fired in this way:
$('.link1').click(function(){
if(!$(this).data('isFirstTime')) {
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
$(this).data('isFirstTime', true);
}
});
This should prevent further click
Upvotes: -1
Reputation: 318362
Use a flag or set a data attribute to make sure the scrolling animation only occurs on the first click.
var flag=true;
$('.link1').click(function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
if (flag) {
$('html, body').animate({scrollTop: '600px'}, 800);
flag = false;
}
});
I'm guessing #div2
should still toggle, but that it just should'nt scroll on every click?
Upvotes: 12
Reputation: 114447
Use a flag
var noRun = 0
$('.link1').click(function(){
if(noRun==1) {
return
}
noRun = 1
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
Upvotes: -1
Reputation: 8301
jQuery .one() http://api.jquery.com/one/
$('.link1').one( 'click', function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
Upvotes: 3
Reputation: 1092
You could unbind that click handler at the end of the handler so that it never triggers again:
$('.link1').off('click');
Upvotes: -1
Reputation: 6458
use the .one
function to bind an event that fires only once.
$('.link1').one('click', function(){
$("#div2").slideUp(function(){$("#div1").slideToggle();});
$('html, body').animate({scrollTop: '600px'}, 800);
});
Upvotes: 1