Reputation: 171
The below HTML and JavaScript is working as expected, but I want to make sure I am using this correctly.
I have two divs but only one needs to be displayed depending on the value of mode
.
HTML:
<body>
<div id="a-div" style="display: none;">
<button id="add" class="btnstyle">Add </button>
</div>
<div id="d-div" style="display: none;">
<button id="delete" class="btnstyle">Delete</button>
</div>
</body>
JS:
//$("#a-div").hide();
//$("#d-div").hide();
var mode = 'add';
//var mode = 'delete';
if (mode === 'add') {
$("#a-div").show();
} else {
$("#d-div").show();
}
This is giving me expected results. Is there a better way of reversing the style="display: none"
attribute?
Upvotes: 2
Views: 9473
Reputation: 8588
Your current code should be working fine, but there are many ways of solving this problem. I would recommend using jQuerys toggle()
:
$("#a-div").toggle(mode === "add");
$("#a-div").toggle(mode === "delete");
Alternatively, you could give them the id´s add-div
and delete-div
and make one of them visible like this:
$("#" + mode + "-div").show();
Upvotes: 1
Reputation: 28174
Another option is to move the styles to css:
html:
<div id="a-div" class="notdisplayed">
<button id="add" class="btnstyle">Add </button>
</div>
<div id="d-div" class="notdisplayed">
<button id="delete" class="btnstyle">Delete</button>
</div>
css:
.notDisplayed {display:none;}
Script:
$("#a-div").addClass("notDisplayed");
$("#d-div").removeClass("notDisplayed");
This method is more general than show/hide, as it can be extended to any style rule.
Upvotes: 0
Reputation: 1446
You need to modify the display property of the inline style attribute.
Like this...
var mode = 'add';
if (mode === 'add') {
$("#a-div")[0].style.display = 'block';
} else {
$("#d-div")[0].style.display = 'block';
}
Or you can use something like inherit
instead of block
.
Upvotes: 0
Reputation: 67525
There's several methods to do this (like you can see in other answers) but i think the show()
function is enough and do the work in your case.
You can also use css()
method of JQuery like following :
$("#a-div").css('display','block');
Hope this helps.
Upvotes: 0
Reputation: 4865
You can use:
$("#a-div").toggle();
Alternatively;
.show()
/ .hide()
.fadeIn()
/ fadeOut()
Upvotes: 0