As per your code, your if
condition is in $(document).ready
. So when this callback will be called, then your if
will be evaluated. However, it will not be called for every click.
On click only following code will be evaluated which does not have any condition.
$("#bokse1").click(function() {
$("#Karusell").animate({
marginLeft: ["+=10px", "linear"],
}, 400, function() {});
});
$('#bokse1').live('click', function() {
currentNextClicked = nextClicked;
nextClicked = currentNextClicked + 1;
console.log(nextClicked)
});
Also, in my understanding, you do not need 2 handlers. It can be handled in 1 as well
$("#bokse1").click(function() {
if (currentNextClicked++ < 2) {
$("#Karusell").animate({
marginLeft: ["+=10px", "linear"],
}, 400, function() {});
}
console.log(currentNextClicked)
});
Also per the code shared, following code doesn't makes sense:
$('#bokse1').live('click', function() {
currentNextClicked = nextClicked;
nextClicked = currentNextClicked + 1;
console.log(nextClicked)
});
You have numeric values stored in 2 variables. If I have to guess, currentNextClicked
refers to current iteration and nextClicked
points to next. But this can be achieved with one variable as well, as nextClicked
will always be currentNextClicked + 1
. Also if you notice, if
in above code is < 2
. That is because, != 2
will be valid if nextClicked
becomes more than 2. Using less than operator would be a better option if you wish to restrict it to 2 values only.
Suggestions:
$().live
has been deprecated. So you will not be able to upgrade easily. So as a suggestion, try to avoid it.
- Declaring a variable without
var|const|let
makes it global variable. Its a bad practice to bleed variables to global scope. So, always use a keyword to declare variable.
- Declaring a variable outside any function will also make it global. So try to even avoid that. Ideally, a variable should have restricted and very specific scope. That means, declaring a variable only in area it will be used.
!=
will perform a loose check. That means 2 != '2'
will return false but it should return true. Try using !==
to enforce that passed variable is a number only.
Sample code:
$(document).ready(function() {
var currentNextClicked = 0;
$("#bokse1").on('click', function() {
if (currentNextClicked++ < 2) {
$("#Karusell").animate({
marginLeft: ["+=10px", "linear"],
}, 400, function() {});
}
console.log(currentNextClicked)
});
});
#bokse1 {
width: 20px;
height: 20px;
background-color: blue;
}
#bokse2 {
width: 20px;
height: 20px;
background-color: red;
}
#Karusell {
width: 30px;
height: 30px;
background-color: indigo;
display: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div id="bokse1"></div>
<div id="bokse2"></div>
<div id="Karusell">
Reference: