Vince Matinde
Vince Matinde

Reputation: 17

How do I loop through HTML elements while executing a function on each element

I am a newbie to Javascript, I wanted to implement a for loop that would go through each div as selected by its class.

The simple idea is to reveal DIVs when I click on a button. But it has to be sequential: I click DIV1 appears, when I click again DIV2 appears and so on. Currently my code only changes the class of one DIV and not the rest. Here are my code samples:

$(document).ready(function(){
    
      // jQuery methods go here...
    var count = document.getElementById("page1").childElementCount;
    
    	for(var i = 0; i < count; i++){
    		
    		var myClass = ".panel" + i; 
    		
    		$("button").click(function(){
    			$(myClass).addClass("showing animated fadeIn")
    		});
    	}
    	
    	
    	
    });/**document ready **/
     .showing{
    	background-color: red;
    	height: 200px; 
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>title</title>
        <link rel="stylesheet" type="text/css" href="mystyle.css">
         <link rel="stylesheet" type="text/css" href="animate.css">
      </head>
      <body>
      
      <button class="one">Click Me!</button>
     
      		<div id="page1">
      			
      			<div class="panel1">
      				
      			</div>
      			<div class="panel2">
      				
      			</div>
      			<div class="panel3">
      				
      			</div>	
      			<div class="panel4">
      				
      			</div>
      		
      		</div><!-- page one -->
      		
      		<div id="trial">
      			
      		</div>
      	
      	<script src="jquery-3.3.1.min.js"></script>
      	<script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
      	<script type="text/javascript" src="trial.js"></script>
      </body>
    </html>

Please let me know what I am missing especially in the for loop or if I can do something else to be able to grab a DIV and add a class every time I click on the button.

Upvotes: 0

Views: 985

Answers (4)

Martin
Martin

Reputation: 2414

What you can do is count the amount of children that you have, and compare the amount of clicks through a given iterator you have to see what should be shown.

I added an extra functionality that hides the elements again once the max amount of divs has been shown.

Hope this helps.

	
$(document).ready(function() {
    $('#page1').children().each(function () {
        $(this).hide();
    });
});
		
var panel="panel";
var pannelNum=0;
var count = $("#page1").children().length;
		
$(".one").on( "click", function() {
    pannelNum=pannelNum+1;
				
    if(pannelNum > count) {
        $('#page1').children().each(function () {
            $(this).hide();
	});
	pannelNum=0;
    }
    else {
        clicked=panel+""+pannelNum;
	$('.'+clicked).show();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="one">Click Me!</button>

<div id="page1">
  <div class="panel1">
    this is panel 1!
  </div>
  <div class="panel2">
    this is panel 2!
  </div>
  <div class="panel3">
    this is panel 3!
  </div>  
  <div class="panel4">
    this is panel 4!
  </div>
</div><!-- page one -->

<div id="trial">

</div>

Upvotes: 0

Daniel Beck
Daniel Beck

Reputation: 21475

You've got this a little bit backwards; you're trying to attach an event handler to the button for each element. Instead, you should have one event handler for the button, which cycles through the elements.

You could set a variable to keep track of which element is currently highlit, but it's easier to just determine that based on the current state of the DOM:

$(document).ready(function() {
  $('button.one').click(function() {
    $('.showing')              // find the current element
      .removeClass('showing')  // clear it
      .next()                  // find its next sibling
      .addClass('showing');    // show that
    if ($('.showing').length === 0) {
      // nothing is showing, so show the first one
      $('#page1 div:eq(0)').addClass('showing')
    }
  })
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
  <div class="panel1"></div>
  <div class="panel2"></div>
  <div class="panel3"></div>
  <div class="panel4"> </div>
</div>

There's a small cheat in the above -- if the current element is the last one, then it won't have a next() to highlight. That's why I waited to check for the case where there's nothing visible until after moving the highlight; that way it will work for both the first click, and for when you need the highlight to loop back around to the first element.

If you intended to have the elements reveal themselves in sequence and not hide earlier ones, just get rid of the .removeClass('showing') line:

$(document).ready(function() {
  $('button.one').click(function() {
    $('.showing')              // find the current element
      .next()                  // find its next sibling
      .addClass('showing');    // show that
    if ($('.showing').length === 0) {
      // nothing is showing, so show the first one
      $('#page1 div:eq(0)').addClass('showing')
    }
  })
})
#page1 div {height: 10px}
#page1 div.showing {background-color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="one">Click Me!</button>
<div id="page1">
  <div class="panel1"></div>
  <div class="panel2"></div>
  <div class="panel3"></div>
  <div class="panel4"> </div>
</div>

Upvotes: 0

robinvrd
robinvrd

Reputation: 1848

Firstly, the HTML attribute class is made for multiple elements with the same style/behaviour. You should use id if it is to dissociate one panel for another.

You have to store a count variable to know which panel has to appear next.

And always try to do what you want in Javascript without jQuery if it is possible !

var i = 1;

function clickBtn() {
  if (!document.getElementById("panel-" + i))
    return;
  document.getElementById("panel-" + i).classList.add("visible");
  i++;
}
.panel {
  width: 50px;
  height: 50px;
  
  display: none;
  
  margin: 5px;
  
  background-color: #bbb;
}

.panel.visible {
  display: block;
}
<button onclick="clickBtn()">click me</button>

<div>
  <div id="panel-1" class="panel"></div>
  <div id="panel-2" class="panel"></div>
  <div id="panel-3" class="panel"></div>
  <div id="panel-4" class="panel"></div>
</div>

Upvotes: 1

Alvin Theodora
Alvin Theodora

Reputation: 946

You could use counter like clickCount instead of for loop

$(document).ready(function(){
  // jQuery methods go here...   
  var clickCount = 1;
  $("button").click(function(){
    var myClass = ".panel" + clickCount; 
    $(myClass).addClass("showing animated fadeIn")
    clickCount++;  
  });
});/**document ready **/
 .showing{
    background-color: red;
    height: 200px; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="mystyle.css">
     <link rel="stylesheet" type="text/css" href="animate.css">
  </head>
  <body>

  <button class="one">Click Me!</button>

        <div id="page1">

            <div class="panel1">

            </div>
            <div class="panel2">

            </div>
            <div class="panel3">

            </div>  
            <div class="panel4">

            </div>

        </div><!-- page one -->

        <div id="trial">

        </div>

    <script src="jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="jquery.touchSwipe.min.js"></script>
    <script type="text/javascript" src="trial.js"></script>
  </body>
</html>

Upvotes: 0

Related Questions