Reputation:
Basically, this advances to the next hidden span when clicked.
The markup:
<div id="facts">
<span>click to cycle</span>
<span>fact 1</span>
<span>fact 2</span>
<span>fact 3</span>
<span>fact 4</span>
</div>
The js:
$(document).ready(function() {
var current = 1;
$('#facts span').click(function() {
// Hide all of them
$('#facts span').hide();
// Unhide the current one:
$('#facts span:eq(' + (current % $('#facts span').length) + ')').show();
// Increment the variable
console.log(current % 4);
current++;
});
// Unhide the first one on load
$('#facts span:first-child').show();
});
What I'm trying to do now is remove the first span after it's been clicked, because it is not necessary for the user to see the 'click to cycle' instruction again.
Upvotes: 0
Views: 186
Reputation: 270637
Assign a specific id to the original one and a class to the others.
<span id='removeme'>click to cycle</span>
<span class='cycleme'>fact 1</span>
<span class='cycleme'>fact 2</span>
<span class='cycleme'>fact 3</span>
<span class='cycleme'>fact 4</span>
Show the removeme
and hide all the others via CSS
#removeme {
display: inline;
}
span.cycleme {
display: none;
}
In the script, bind a click event to the original one to simply remove it. The subsequent ones get the same handler as they had before.
$(document).ready(function() {
// Initialize
var current = 1;
// Bind the first one's onclick to remove itself
$('#removeme').click(function() {
$(this).remove();
// And display the first one
$('#facts span:first-child').show();
});
// Target the others via their class
$('#facts span.cycleme').click(function() {
// Hide all of them
$('#facts span').hide();
// Unhide the current one:
$('#facts span:eq(' + (current % $('#facts span.cycleme').length) + ')').show();
// Increment the variable
current++;
});
});
Upvotes: 1
Reputation: 4783
Here you go
HTML
<div id="facts">
<span id='remove'>click to cycle</span>
<span>fact 1</span>
<span>fact 2</span>
<span>fact 3</span>
<span>fact 4</span>
</div>
JQuery
$(document).ready(function() {
var current = 1;
$('#facts span').click(function() {
$('#remove').remove();
// Hide all of them
$('#facts span').hide();
// Unhide the current one:
$('#facts span:eq(' + (current % $('#facts span').length) + ')').show();// Increment the variable
console.log(current % 4);
current++;
});
// Unhide the first one on load
$('#facts span:first-child').show();
});
Upvotes: 1