Skip to content Skip to sidebar Skip to footer

Check Spans And Remove The First-child

Basically, this advances to the next hidden span when clicked. The markup:
click to cycle fact 1

Solution 1:

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++;
   });
});​

Here is the live example


Solution 2:

Here you go

Fiddle

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();
});

Post a Comment for "Check Spans And Remove The First-child"