List of things I tried
- .removeClass and addClass
- show() and hide();
- changing the css
To begin: Yes, I do have onl oad in the beginning of my script, and all of the other components work perfectly. Yes, I have tried Googling, and nothing fixes the problem. This is not a dublicate.
$("button").click(function(){
$("block").addClass("hidden"); //class hidden is display: none
$("block").removeClass("hidden");
}
This is my code. No, block is not a class or ID, I am gonna use it as an example. Please help, I do not know what I have done wrong in my code and why this doesn't work.
By the way, adding the class works, removing it doesn't.
HTML:
<block>A</block>
CodePudding user response:
is the event being triggered ? i know that click
is depricated but it should be supported for compatibility , you can also print the button and look if the class is still there, the proper way should be using on
$("button").on("click", function () {
$("block").addClass("hidden"); //class hidden is display: none
$("block").removeClass("hidden");
console.log($("block")) //look for classList
})
if you just want to hide a element you can also use
$("block").hide()
$("block").show()
or with fade in/out
$("block").fadeOut(500) // number of ms
$("block").fadeIn(500)
one more thing in case you're confusing css properties and classes, a css property can be changed using css
$("block").css({display:"hidden"})
$("block").css({display:"block"})
CodePudding user response:
Maybe this is what you are aiming at?
$("button").on("click",function(){
$("block").toggleClass("hidden")
})
.hidden { visibility: hidden }
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<block>A</block>
<button>hide/show</button>
Instead of display
I used the visibilty
attribute to make sure nothing moves around. The jQuery method .toggleClass("hidden")
then adds or removes the class "hidden".
And, since you actually want to see things moving around, you can do this:
$("button").on("click",function(){
$("block").toggleClass("hidden")
})
.hidden { display: none }
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<block>A</block>
<button>hide/show</button>
Hint: In a real application you should probably make the selector "block"
a bit more specific. With the current script version all <block>
elements will be affected. A lightweight way of targeting only the element that comes before the button would be to use something like $(this).previous()
.