Search code examples
javascriptjqueryhtmlcssextjs3

highlight and un-highlight item selected in jquery


I have a dynamic list of image thumbnails. Every time an image is selected I want to unselect the currently selected image and select the newly clicked image. The html looks like below:

<ul class="imgList">
    <li>
        <div id="item1" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
    <li>
        <div id="item2" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
    <li>
        <div id="itemn" class="imgStyle" order="{#}" imgId="{imgId}">
            <img src="{imgPath}"/>
        </div>
    </li>
</ul>

And I use jquery to bind the items on click event like this:

$( ".imgStyle img").bind( "click", function() {
    $(item1).css("border", "5px solid grey");
}

I'm easily able to select/highlight the item clicked. But how do I unselect the previously highlighted item (div)? Thanks!


Solution

  • You should use CSS classes :

    .selected { border: 5px solid gray;}
    
    $('.imgList').on('click','img', function() {
       $(this).parents('.imgList').find('.selected').removeClass('selected').end().end().addClass('selected');
    });