javascript - How to access "this" inside a closure? -
i'm new javascript , jquery , i'm having trouble bit of code.
html:
<div class="toggle" style="display: block; width: 200px; height: 200px; background-color: red;">test</div>
javascript:
jquery(document).ready( function() { jquery(".toggle").on("click", function() { console.log("let toggling begin!"); jquery(this).slidetoggle(600, function(){ // slide settimeout(function(){ // wait 4 sec, slide down jquery(this).slidetoggle(600) }, 4000); }); }); } );
so idea click on div, slides up, 4 seconds later slides down. doesn't work.
jsfiddle: http://jsfiddle.net/zeqn9/2/
however, if change this
inside each of closures ".toggle"
, work.
jsfiddle: http://jsfiddle.net/yzxmb/
so issue use of this
.
i tried passing this
parameter each of 2 closure functions, gave error unexpected token this
.
how can access this
variable inner functions?
create reference this
in slidetoggle function.
jquery(document).ready( function() { jquery(".toggle").on("click", function() { console.log("let toggling begin!"); jquery(this).slidetoggle(600, function(){ // slide var self = this; // <-- notice settimeout(function(){ // wait 4 sec, slide down jquery(self).slidetoggle(600) }, 4000); }); }); } );
Comments
Post a Comment