snipt

Ctrl+h for KB shortcuts

JavaScript

jQuery. Steps in $.each()

1
2
3
4
5
6
var eachItem = 4; // someFunction() will work on 1st, 5th, 9th ... element
$('.selector').each(function(i) {
	if(i++ % eachItem === 0) { // to select 4th, 8th etc. elements use ++i instead of i++
		someFunction();
	}
});

Description

If you want to work with, for example, each 4 element width .selector, use this "hack" :)
https://snipt.net/embed/48ddd2a0e4e231a034ac64ebf3fde8ac/
/raw/48ddd2a0e4e231a034ac64ebf3fde8ac/
48ddd2a0e4e231a034ac64ebf3fde8ac
js
JavaScript
6
2019-08-24T20:44:40
True
False
False
/api/public/snipt/129927/
jquery-steps-in-each
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="kd">var</span> <span class="nx">eachItem</span> <span class="o">=</span> <span class="mi">4</span><span class="p">;</span> <span class="c1">// someFunction() will work on 1st, 5th, 9th ... element</span> </span><span id="L-2"><a name="L-2"></a><span class="nx">$</span><span class="p">(</span><span class="s1">&#39;.selector&#39;</span><span class="p">).</span><span class="nx">each</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">i</span><span class="p">)</span> <span class="p">{</span> </span><span id="L-3"><a name="L-3"></a> <span class="k">if</span><span class="p">(</span><span class="nx">i</span><span class="o">++</span> <span class="o">%</span> <span class="nx">eachItem</span> <span class="o">===</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// to select 4th, 8th etc. elements use ++i instead of i++</span> </span><span id="L-4"><a name="L-4"></a> <span class="nx">someFunction</span><span class="p">();</span> </span><span id="L-5"><a name="L-5"></a> <span class="p">}</span> </span><span id="L-6"><a name="L-6"></a><span class="p">});</span> </span></pre></div> </td></tr></table>
each, function, hack, jquery