Reputation: 638
I'm trying to completely hide a span tag when the visibility is "hidden" by using display: none which works perfectly, only problem is the else statement is not working at all. I mean, it should alert and display: block but it's not at all.
$(document).ready(function () {
$(".compPass").each(function () {
if ($('.compPass').css("visibility") == "hidden") {
$('.compPass').css("display", "none");
}
else {
alert('');
$('.compPass').css("display", "block");
}
});
});
Upvotes: 0
Views: 46
Reputation: 6938
Else statement is not working since, you are not setting the visible
property as follows :
$(document).ready(function () {
$(".compPass").each(function () {
if ($('.compPass').css("visibility") == "hidden"){
$('.compPass').css("display", "none");
}else{
$('.compPass').css("display", "block");
$('.compPass').css("visibility", "visible");
}
});
});
Demo : http://jsbin.com/oyEhEpoT/1/
Like @RGraham suggested, .comPass
will toggle all html elements with class .comPass
. If you need to use a particular one, then you should be using like a click function or any event and inside that use :
$(document).ready(function () {
$(document).on("click", ".comPass", function (e) {
if ($(this).css("visibility") == "hidden"){
$(this).css("display", "none");
}else{
$(this).css("display", "block");
$(this).css("visibility", "visible");
}
});
});
Upvotes: 0
Reputation: 78525
By referencing $(".compPass")
inside the .each, you are referencing all elements on the page with that class. Use $(this)
instead to reference the current element:
$(document).ready(function () {
$(".compPass").each(function () {
if ($(this).css("visibility") == "hidden") {
$(this).css("display", "none");
}
else {
alert('');
$(this).css("display", "block");
}
});
});
You could also replace this with a single function using the function overload of .css():
$(".compPass").css("display", function() {
return $(this).css("visibility") === "hidden" ? "none" : "block";
});
Here is a jsFiddle of the css overloaded function.
Upvotes: 4