Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>With your current HTML:</p> <pre><code>$('input').focus(function(){ $(this).prev().addClass('active'); }).blur(function(){ $(this).prev().removeClass('active'); }); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/A8J3E/" rel="nofollow">JS Fiddle demo</a>.</p> <p>Or, with <code>on()</code> (assuming you're using jQuery 1.7, or above):</p> <pre><code>$('input').on('focus blur', function(e){ var prev = $(this).prev(); prev[e.type == 'focus' ? 'addClass' : 'removeClass']('active'); }); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/A8J3E/1/" rel="nofollow">JS Fiddle demo</a>.</p> <p>More abstracted (so the HTML stucture doesn't matter), selecting by the <code>for</code> attribute:</p> <pre><code>$('input').on('focus blur', function(e){ var label = $('label[for="' + this.id + '"]'); label[e.type == 'focus' ? 'addClass' : 'removeClass']('active'); }); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/A8J3E/2/" rel="nofollow">JS Fiddle demo</a>.</p> <p>References:</p> <ul> <li><a href="http://api.jquery.com/addClass/" rel="nofollow"><code>addClass()</code></a>.</li> <li><a href="http://api.jquery.com/attribute-equals-selector/" rel="nofollow">Attribute-equals (<code>[attribute="value"]</code>) selector</a>.</li> <li><a href="http://api.jquery.com/blur/" rel="nofollow"><code>blur()</code></a>.</li> <li><a href="http://api.jquery.com/focus/" rel="nofollow"><code>focus()</code></a>.</li> <li><a href="http://api.jquery.com/on/" rel="nofollow"><code>on()</code></a>.</li> <li><a href="http://api.jquery.com/prev/" rel="nofollow"><code>prev()</code></a>.</li> <li><a href="http://api.jquery.com/removeClass/" rel="nofollow"><code>removeClass()</code></a>.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload