javascript - Jquery to check if inside element -
i'm trying add class element if user has clicked inside it.
all usual rules apply - "inside" means inside child, grandchild etc.
if inside, need add class - if outside class should removed.
i've pieced example, works, non-javascript man, i'd appreciate feedback whether it's reasonable approach, , if can improved on - improved, refer jquery/javascript performance.
any advice appreciated.
$("body").click(function (e) { $fs = $(e.target).closest("fieldset.expand"); if ($fs.length) { $fs.addclass("focus"); } else { $("fieldset.expand").removeclass("focus"); } });
<body> <fieldset class="expand"> <input type="text" /> <input type="text" /> <input type="text" /> </fieldset> </body>
makes fieldset
focusable (but not tabbable), using tabindex
attribute negative value. set logic using focusin focusout
events:
$('fieldset.expand').on('focusin focusout', function() { $(this).toggleclass('focus', $(this).find('*').addback().is(':focus')); });
fieldset.focus { outline: 0; background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <fieldset tabindex="-1" class="expand"> <input type="text" /> <input type="text" /> <input type="text" /> </fieldset>
Comments
Post a Comment