Issue
I'm working on side php project and I'm just wondering how can I modify my code so that there will be only one button instead of two.
Right now, I have show and hide buttons. I'm thinking about having only one button and it will display Hide option first. after a user click Hide option then it'll change it to show.
<button type="button" class="btn btn-light" onClick="hide_div('transpose-keys');">Hide</button>
<button type="button" class="btn btn-light" onClick="show_div('transpose-keys');">Show</button>
function hide_div(e) {
$(".c").hide()
$("."+e).hide()
}
function show_div(e) {
$(".c").show()
$("."+e).show()
}
Solution
- You need to define a CSS class to hide elements,
{ display: none }
. - That class will be injected to the target element to hide it or removed to get it back to be displayed.
setHiddable("hide-show", "target");
/**
* Ideal to set a hide/show relationship between only two elements
* @param {string} btnId The ID of the button that toggle the view
* @param {string} elementId The ID of the element to be toggled
*/
function setHiddable(btnId, elementId) {
const btn = document.querySelector(`#${btnId}`);
// Listen to clicks
btn.addEventListener("click", (ev) => {
const targetEl = document.querySelector(`#${elementId}`);
// Hide if shown
// Show if hidden
targetEl.classList.toggle("hidden");
});
}
#target {
height: 100px;
width: 100px;
background: red;
}
.hidden{
display: none;
}
<div id="target"> This is the element that you want to show and hide on click </div>
<button type="button" class="btn btn-light" id="hide-show">TOGGLE VIEW</button>
Answered By - medilies
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.