WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Change CSS display Property to none or block using jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the jQuery css() Method

You can use the jQuery css() method to change the CSS display property value to none or block or any other value. The css() method apply style rules directly to the elements i.e. inline.

The following example will change the display of a DIV element on button click:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Change CSS display Property to none or block</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    #myDiv{
        padding: 20px;
        background: #abb1b8;
        margin-top: 10px;
    }
</style>
<script>
$(document).ready(function(){
    // Set div display to none
    $(".hide-btn").click(function(){
        $("#myDiv").css("display", "none");
    });
    
    // Set div display to block
    $(".show-btn").click(function(){
        $("#myDiv").css("display", "block");
    });
});
</script>
</head>
<body>
    <button type="button" class="hide-btn">Display none</button>
    <button type="button" class="show-btn">Display block</button>
    <div id="myDiv">#myDiv</div>
</body>
</html>

Alternatively, if don't want to bother about the initial value of the element's display property, but you want to toggle between its initial value and none, you can simply use the jQuery show(), hide() or just toggle() method. The following example shows how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Toggle CSS display of an Element</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<style>
    #myDiv{
        padding: 20px;
        background: #abb1b8;
        margin-top: 10px;
    }
</style>
<script>
$(document).ready(function(){
    // Hide div by setting display to none
    $(".hide-btn").click(function(){
        $("#myDiv").hide();
    });
    
    // Show div by removing inline display none style rule
    $(".show-btn").click(function(){
        $("#myDiv").show();
    });
    
    // Toggle div display
    $(".toggle-btn").click(function(){
        $("#myDiv").toggle();
    });
});
</script>
</head>
<body>
    <button type="button" class="hide-btn">Hide</button>
    <button type="button" class="show-btn">Show</button>
    <button type="button" class="toggle-btn">Toggle</button>
    <div id="myDiv">#myDiv</div>
</body>
</html>

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties