Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to target items of the same class that are not clicked using jQuery?

Tags:

jquery

What I have is 3 divs of the same class but with a unique id and when I click one box I would like to hide the other 2.

This isn't a problem and I could achieve it with a few if/elses or a case statement perhaps but I was wondering if there was a more generic/efficient way to hide all elements of the same class that isn't the one that was clicked?

<div id="boxes">
    <div id="box1" class="box">Box 1</div>
    <div id="box2" class="box">Box 2</div>
    <div id="box3" class="box">Box 3</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('.box').click(function() {
        $(this).html('hi');
        if ($(this).attr('id') == 'box1')
        {
            $('#box2').hide('slow');
            $('#box3').hide('slow');
        }
       .......... more if's     
    });
});
</script>
like image 938
martincarlin87 Avatar asked Dec 22 '22 05:12

martincarlin87


1 Answers

You can use the .not filter function to refer to "the other" boxes. This way the code will work even if the boxes are not necessarily siblings in the DOM tree, or if there are some additional siblings that are not boxes.

var $boxes = $('.box');
$boxes.click(function() { 
    $(this).html('hi'); 
    $boxes.not(this).hide('slow');
}); 

Notice that I 'm caching the result of $('.box') for performance -- doubtless it will not be noticeable, but there's no reason not to do that.

like image 182
Jon Avatar answered May 04 '23 17:05

Jon