I Can't Get The Or Operator To Work Properly
For some reason I do not understand, the OR operator does not work properly. In below example I am trying to create a hover effect with jquery, which is only applied if the id of t
Solution 1:
Change the or's to and's.
$(document).on("mouseenter", ".123456", function() {
if (this.id != 'f1' && this.id != 'c1') {
$(this).css("background-color", "green")
$(this).find('span').css("color", "red")
}
});
$(document).on("mouseleave", ".123456", function() {
if ((this.id != 'f1') && (this.id != 'c1')) {
$(this).css("background-color", "white")
$(this).find('span').css("color", "black")
}
});
This way, the hover effect will only be applied to elements whose id is not c1 AND to elements whose id is not f1.
Solution 2:
You could take logical AND &&
, because you need to exclude both, no just one.
$(document).on("mouseenter", ".123456", function() {
if (this.id != 'f1' && this.id != 'c1') {
$(this).css("background-color", "green")
$(this).find('span').css("color", "red")
}
});
$(document).on("mouseleave", ".123456", function() {
if (this.id != 'f1' && this.id != 'c1') {
$(this).css("background-color", "white")
$(this).find('span').css("color", "black")
}
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="a1"class="123456"><span>a1</span></div><divid="f1"class="123456"><span>f1</span></div>
Solution 3:
In this case you should use &&
instead of ||
, since it will evaluate to true
for the other case, and thus true
for the whole expression, always.
Think of your logic as !( (id == A) || (id == B) )
. The simplification of that is (id != A) && (id != B)
, due to DeMorgan’s laws.
Solution 4:
The problem is that you should be using logical AND (&&
), not logical OR (||
).
$(document).on("mouseenter", ".123456", function() {
if (this.id != 'f1' && this.id != 'c1') {
$(this).css("background-color", "green")
$(this).find('span').css("color", "red")
}
});
$(document).on("mouseleave", ".123456", function() {
if ((this.id != 'f1') || (this.id != 'c1')) {
$(this).css("background-color", "white")
$(this).find('span').css("color", "black")
}
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="a1"class="123456"><span>a1</span></div><divid="f1"class="123456"><span>f1</span></div>
Also, you can achieve the exact same result with only CSS and no JavaScript. This would, not only be much simpler, but it is also much more efficient.
.hover:not(#f1):hover:not(#c1):hover {
background-color:green;
color:red;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="a1"class="hover"><span>a1</span></div><divid="f1"class="hover"><span>f1</span></div>
Post a Comment for "I Can't Get The Or Operator To Work Properly"