jqueryfadeinfadeto

jQuery .fadeTo() method with .click()


I am using .fadeToggle() to fade in & out a div element. Here is its HTML and script

<div id="image2"><img src="http://placehold.it/350x350" /> </div>
<div class="divButton2"><br/> Button 3!</div>

  $(document).ready(function(){
    $('.divButton2').click(function(){
        $('div#image2').fadeToggle('slow');
    });
});

Now I am using .fadeTo() method with semi-transparent opacity

 $(document).ready(function(){
    $('.divButton2').click(function(){
        $('#image2').fadeTo('slow', 0.5);
    }); 
});

and once I click a button it is halfway faded out now I would like to click again so it fades back in completely. How can I do that ?


Solution

  •  $(document).ready(function(){
        $('.divButton2').click(function(){
         if($('#image2').css('opacity') == 1){
           $('#image2').fadeTo('slow', 0.2);
         }else{
           $('#image2').fadeTo('slow', 1);
         }  
        }); 
    });
    

    or you can use .animate()

     $(document).ready(function(){
            $('.divButton2').on('click',function(){
             if($('#image2').css('opacity') == 1){
               $('#image2').animate({'opacity': 0.2}, 1000);
             }else{
               $('#image2').animate({'opacity': 1}, 1000);
             }  
            }); 
        });
    

    JSFIDDLE