简体   繁体   中英

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>

PS: Got my source from the accepted answer in this link: jQuery toggle CSS?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM