0

i have image set div tag like below

<div style="width: 600px; background: #CCC;padding: 50px;" class="jjj">
<img src="http://www.nasa.gov/images/content/297522main_image_1244_946-710.jpg" class="ddd"  width="200"/>
<img src="http://www.nasa.gov/images/content/297522main_image_1244_946-710.jpg" class="ddd"  width="200"/>
<img src="http://www.nasa.gov/images/content/297522main_image_1244_946-710.jpg" class="ddd"  width="200"/>
</div>

My CSS is

<style>
.ddd:hover{
            transform: scale(1.2);
-ms-transform: scale(1.2); /* IE 9 */
-webkit-transform: scale(1.2); /* Safari and Chrome */
-o-transform: scale(1.2); /* Opera */
-moz-transform: scale(1.2); /* Firefox */
        }

        .selectedd{
            transform: scale(1.2);
-ms-transform: scale(1.2); /* IE 9 */
-webkit-transform: scale(1.2); /* Safari and Chrome */
-o-transform: scale(1.2); /* Opera */
-moz-transform: scale(1.2); /* Firefox */
border:2px inset silver;
        }
</style>

i need to select image when user click on it (change the class), i added the script for this and it working, but how can i deselect this image when user clicks on out side, i mean on div tag. my jQuery

<script>
$(function(){
    $('.ddd').click(function(){
        ff=this;
        $('.ddd').removeClass('selectedd')
        $(ff).addClass('selectedd')
    }); 
    });
</script>

Please help me. thank you

Suneth Kalhara
  • 1,116
  • 4
  • 16
  • 40

1 Answers1

3

Use stopPropagation() when user clicks over an image, otherwise capture the click event on the body (or other element) and remove the selectedd class on the image (if any)

$(function(){
    var ff;

    $('.ddd').on('click', function(evt) {
        ff = $(this);
        evt.stopPropagation();
        $('.ddd').removeClass('selectedd')
        ff.addClass('selectedd')
    }); 
    $('body').on('click', function() {
        if (ff.length) {
           ff.removeClass('selectedd')
        }
    });
});
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177