Reputation: 3
I'm quite new to js and jquery, and I find that jquery-starters all run into the same if else problem. How much I search on other sites or here, the examples are to complicated at this point ;) Can anyone help me with this very basic statement, would mean a lot...
The problem: I want to hide a button after 4 clicks. I'm using a variable to count the clicks, but the result is that the button is hidden after 1 click, not 4. Anyone?
<script>
$(document).ready(function(){
var x = 0;
$(".but_mirror_right").click(function(){
$("#spiegel_links").animate({left:'+=200%'}, 6000);
x += 1;
alert(x);
if (x = 4) {
$("#but_right").hide();
}
else {
$("#but_right").show();
}
});
});
</script>
Upvotes: 0
Views: 55
Reputation: 15614
$(document).ready(function() {
var x = 0;
$(".but_mirror_right").click(function() {
x ++;
console.log(x);
if (x >= 4) {
$("#but_right").hide();
} else {
$("#but_right").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="but_mirror_right">button</button>
<button id="but_right">toggle</button>
<p>Button will disable after 4 click</p>
you are assining 4 to x. check for '=' '==' '==='
operator
Upvotes: 0
Reputation: 2769
Try changing
if (x = 4) {
to
if (x == 4) {
or
if (x === 4) {
=
is an assignment operator and the statement x = 4
will always return true, that is why the code is not working as expected. You should replace it with ==
or ===
Upvotes: 1
Reputation: 22500
Change if(x=4)
to (x==4)
$(document).ready(function() {
var x = 0;
$(".but_mirror_right").click(function() {
// $("#spiegel_links").animate({
// left: '+=200%'
// }, 6000);
x += 1;
console.log(x);
if (x == 4) {
$("#but_right").hide();
} else {
$("#but_right").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="but_mirror_right">button</button>
<button id="but_right">toggle</button>
Upvotes: 0
Reputation: 41520
Change this line
if (x = 4) {
to this
if (x === 4) {
The first one assigns 4 to x
, which always evaluates to true, so that branch is always followed. The second tests equality.
Upvotes: 1