Reputation: 332
I need some help here. I'm trying to make my own content slider writing my own code but can't seem to figure this out. I am new and learning all this, so any help would be appreciated. What i'm trying to do is when the user clicks next, it will hide the current slide and display the next. I'm trying to do this with a global variable, but i'm not sure how to maintain the global variable being updated from within the function. Here is some code, I know my explanation isn't very good.
$(function () {
var i = '';
$('.next').click(function() {
$('.slide' + i).hide();
i++;
console.log(i);
if(i <= 4) {
$('.slide' + i).show();
}
else {
var i = 1;
$('.slide' + i).show();
i++;
console.log(i);
}
});
});
and the markup
<div class="outerWrapper wrapperWidthHeight">
<div class="innerWrapper wrapperWidthHeight slide1">
1
</div>
<div class="innerWrapper wrapperWidthHeight slide2">
2
</div>
<div class="innerWrapper wrapperWidthHeight slide3">
3
</div>
<div class="innerWrapper wrapperWidthHeight slide4">
4
</div>
</div>
<div class="next">NEXT</div>
and the CSS
.wrapperWidthHeight {
margin:auto;
width:900px;
height:600px;
}
.outerWrapper {
overflow:hidden;
position:relative;
margin-top:10px;
border:1px solid black;
border-radius:15px;
box-shadow: 2px 2px 5px 5px #888;
}
.innerWrapper {
position:absolute;
text-align:center;
padding:0;
margin:auto;
}
.slide1 {
display:block;
}
.slide2, .slide3, .slide4 {
display:none;
}
.next{
display:block;
margin:auto;
}
Upvotes: 1
Views: 1315
Reputation: 4906
$(function () {
var i = 1; // should be a number
// this var IS NOT global, nut it is available to
// the scope of the anonymous function
$('.next').click(function() {
// accessing i here is only accessing via
// the scope chain, i isn't "global" this way
$('.slide' + i).hide();
i++;
console.log(i);
if(i > 4) {
i = 1; // DON'T write "var" here, doing so
// defines a NEW local variable i in the local scope
}
$('.slide' + i).show();
// you don't need to increment i here,
// it's already incremented by setting from 4+ to 1
console.log(i);
});
});
Upvotes: 1
Reputation: 3110
Just a couple tweaks to what you had got it working for me:
$(document).ready(function () {
var i = 1;
$('.next').click(function () {
$('.slide' + i).hide();
i++;
console.log(i);
if (i <= 4) {
$('.slide' + i).show();
}
else {
i = 1;
$('.slide' + i).show();
console.log(i);
}
});
});
Upvotes: 1
Reputation: 1162
Try creating your global variable as a member of the window object, outside of your function. You can put something like this, just outside of your function:
window.i = 0;
if you're going to increment it, you should also probably initialize it to zero, instead of an empty string, I'm not saying it will cause a problem, just that it's good practice.
Upvotes: 0