jessica
jessica

Reputation: 1687

Making div invisible and visible using toggle in jQuery

I have a div where when you click it, it's suppose to turn invisible, and when you click on it again, it's suppose to turn visible. But something's wrong with my code. Please take a look:

<div id = "id"> Hello </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript"> 

//*****************************************************************************

function toggleOnClick($id){

$("#"+$id).click(function() {   
$("#"+$id).toggle(

function () {
$(this).css({visibility: "hidden"});
}, 
function () {
$(this).css({visibility: "visible"});

}); //end of $("#"+$id).toggle

}); //end of $("#"+$id).click(function()    

} //end of function toggleOnclick($id)

//*****************************************************************************

$(document).ready(function(){

toggleOnClick("id");

});         

</script>

P.S: Got my source from the accepted answer in this link: jQuery toggle CSS?

Upvotes: 2

Views: 466

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

tggle() will toggle between display property so it will not retain place for element after it hides, You need to use css() with callback and update its opacity, it will retain it's place.

Update : The click event will not fire on element with visibility: hidden so you need to use opacity:0

Callback in css() is a function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. ( Taken from http://api.jquery.com/css/#css-propertyName-function )

<div id="id">Hello</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
  //*****************************************************************************

  function toggleOnClick($id) {

      $("#" + $id).click(function() {
        $("#" + $id).css('opacity', function(i, v) {
          return v == 0 ? 1 : 0; //end of $("#"+$id).toggle
        });
      }); //end of $("#"+$id).click(function()    

    } //end of function toggleOnclick($id)

  //*****************************************************************************

  $(document).ready(function() {

    toggleOnClick("id");

  });
</script>

Upvotes: 3

Related Questions