Please note, this is a STATIC archive of website www.tutorialrepublic.com from 10 Sep 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

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:

Advertisements
Bootstrap UI Design Templates