2

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?

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

10 Comments

Can you explain the callback? And what's inside it?
Also the callback function have 2 parameters. 'i' and 'v', but I don't see the 'i' anywhere. What does it do?
@jessica : i is index and v is old value
@jessica : we don't need i , but we want v
Why is i included in the parameter if we don't need it? o.O
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.