× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

JavaScript: Modifying an element inside an event handler for that element

Jessamyn Smith
Sep 22, 2015
<p>You must be very careful when modifying an element inside an event handler for that element, otherwise you might create an infinite loop. Let's say you have code something like the following:</p> <pre><strong>var </strong>updateHeight = <strong>function</strong>() { <strong>var </strong>newHeight = ...; <em>// Some fancy calculations to get new height </em><em> </em><strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">css</span>(<strong>'min-height'</strong>, <span style="color:#458383">newHeight</span>) }; <strong>var </strong><em>resizeHandler </em>= <strong>function </strong>() { <em>updateHeight</em>(); }; <strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">bind</span>(<strong>'resize'</strong>, <em>resizeHandler</em>);</pre> <p>This is dangerous because in some cases setting min-height will change the height of the element with class content, triggering the resize event, which changes the min-height, and so on forever. </p> <p>You can safely deal with such situations by unbinding the event handler before you modify the element:</p> <pre><strong>var </strong>updateHeight = <strong>function</strong>() { <strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">bind</span>(<strong>'resize'</strong>); <strong>var </strong>newHeight = ...; <em>// Some fancy calculations to get new height </em><em> </em><strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">bind</span>(<strong>'resize'</strong>, <em>resizeHandler</em>); <strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">css</span>(<strong>'min-height'</strong>, <span style="color:#458383">newHeight</span>) }; <strong>var </strong><em>resizeHandler </em>= <strong>function </strong>() { <em>updateHeight</em>(); }; <strong>$</strong>(<strong>".content"</strong>).<span style="color:#7a7a43">bind</span>(<strong>'resize'</strong>, <em>resizeHandler</em>);</pre>
comments powered by Disqus