Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Set the Value of Input Text Box using jQuer... >>
<< How to Get the Value in an Input Text Box using jQ...