3 Replies - 254 Views - Last Post: 07 June 2017 - 10:53 PM

#1 au.ceif.  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 25-April 17

Length of Lis is always four

Posted 07 June 2017 - 06:30 AM

Good morning. I wrote a javascript code and it doesn't matter what I do, when I insert or delete an element, for the length of li elements, I always get the value 4, when I use a variable that contains a JQuery selection with the length property. When I use the JQuery selection itself, I successfully update the span with the number of li elements. Why does this happen? I wrote some comments in the javascript code explaining the situation. Thank you for the help.

HTML code

<!DOCTYPE html>
<html>
  <head>
    <title>Javascript &amp; jQuery - Chapter 7: Introducing jQuery - Example</title>
    <link rel="stylesheet" href="css/c07.css" />
    <meta charset="UTF-8">
  </head>
  <body>
    <div id="page">
      <h1 id="header">List</h1>
      <h2>Buy groceries <span id="counter"></span></h2>
      <ul>
        <li id="one" class="hot"><em>fresh</em> figs</li>
        <li id="two" class="hot">pine nuts</li>
        <li id="three" class="hot">honey</li>
        <li id="four">balsamic vinegar</li>
      </ul>
      <div id="newItemButton"><button href="#" id="showForm">new item</button></div>
      <form id="newItemForm">
        <input type="text" id="itemDescription" placeholder="Add description" />
        <input type="submit" id="add" value="add" />
      </form>
    </div>
    <script
			  src="https://code.jquery.com/jquery-3.2.1.min.js"
			  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
			  crossorigin="anonymous">
    </script>
    <script src="js/default.js"></script>
  </body>
</html>





CSS Code

@import url(http://fonts.googleapis.com/css?family=Oswald);

body {
  background-color: #000;
  font-family: 'Oswald', 'Futura', sans-serif;
  margin: 0; 
  padding: 0;}

#page {
  background-color: #403c3b;
  margin: 0 auto 0 auto;
  position: relative;
  text-align: center;}
  /* Responsive page rules at bottom of style sheet */

h1 {
  background-image: url(../images/kinglogo.png);
  background-repeat: no-repeat;
  background-position: center center;
  text-align: center;
  text-indent: -1000%;
  height: 75px;
  line-height: 75px;
  width: 117px;
  margin: 0 auto 0 auto;
  padding: 30px 10px 20px 10px;}

h2 {
  color: #fff;
  font-size: 24px;
  font-weight: normal;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: .3em;
  display: inline-block;
  margin: 0 0 23px 0;}

h2 span {
  background-color: #fff;
  color: #000;
  font-size: 12px;
  text-align: center;
  letter-spacing: 0;
  display: inline-block;
  position: relative;
  border-radius: 50%;
  top: -5px;
  height: 22px;
  width: 26px;
  padding: 4px 0 0 0;}

ul {
  border:none;
  padding: 0;
  margin: 0;}

li {
  background-color: #ec8b68;
  color: #fff;
  border-top: 1px solid #fe9772;
  border-bottom: 1px solid #9f593f;
  font-size: 24px;
  letter-spacing: .05em;
  list-style-type: none;
  text-shadow: 2px 2px 1px #9f593f;
  text-align: left;
  height: 50px;
  padding-left: 1em;
  padding-top: 10px;}

li a {
  color: #fff;
  background-image: url('../images/icon-link.png');
  background-position: right, center;
  background-repeat: no-repeat;
  text-decoration: none;
  padding-right: 36px;}

li.complete a {
  background-image: none;}

p {
  background-color: #fff;
  color: #666; 
  padding: 10px;
  display: inline-block;
  margin: 20px auto 20px auto;
  width: 80%;
  border-radius: 5px;
  text-align: center;}

.hot {
  background-color: #d7666b;
  color: #fff;
  text-shadow: 2px 2px 1px #914141;
  border-top: 1px solid #e99295;
  border-bottom: 1px solid #914141;}

.cool {
  background-color: #6cc0ac;
  color: #fff;
  text-shadow: 2px 2px 1px #3b6a5e;
  border-top: 1px solid #7ee0c9;
  border-bottom: 1px solid #3b6a5e;}

.complete {
  background-color: #999;
  color: #fff;
  background-image: url("../images/icon-trash.png");
  background-position: right, center;
  background-repeat: no-repeat;
  border-top: 1px solid #666;
  border-bottom: 1px solid #b0b0b0;
  text-shadow: 2px 2px 1px #333;}

.complete a {display:block;}

.favorite {
  background-image: url('../images/icon-heart.png');
  background-position: right, center;
  background-repeat: no-repeat;}

em.seasonal
 {
  background-image: url('../images/icon-calendar.png');
  background-position: left  center;
  background-repeat: no-repeat;
  padding-left: 30px;}


/* FORM STYLES */

form {
  padding: 0 20px 20px 20px;}

label {
  color: #fff;
  display: block;
  margin: 10px 0 10px 0;
  font-size: 24px;}

input[type='text'], input[type='password'], textarea {
  background-color: #999;
  color: #333;
  font-size: 24px;
  width: 96%;
  padding: 4px 6px;
  border: 1px solid #999;
  border-radius: 8px;}

input[type='submit'], a.add, button, a.show {
  background-color: #cb6868;
  color: #f3dad1;
  border-radius: 8px;
  border: none;
  padding: 8px 10px;
  margin-top: 10px;
  font-family: 'Oswald', 'Futura', sans-serif;
  font-size: 18px;
  text-decoration: none;
  text-transform: uppercase;}

input[type='submit'], a.add, button {
  float: right;} 

input[type='text']:focus, input[type='password']:focus, textarea:focus {
  border: 1px solid #fff;
  background-color: #fff;
  outline: none;}

input[type='submit']:hover, a.add:hover, a.show:hover {
  background-color: #000;
  color: #fff;
  cursor: pointer;}


::-webkit-input-placeholder {color: #403c3b; font-family: arial, sans-serif;}
:-moz-placeholder { /* Firefox 18- */ color: #403c3b; font-family: arial, sans-serif;}
::-moz-placeholder {  /* Firefox 19+ */ color: #403c3b; font-family: arial, sans-serif;}
:-ms-input-placeholder { color: #403c3b; font-family: arial, sans-serif;}


textarea {
  width: 96%;
  height: 5em;
  line-height: 1.4em;}

select, option {
  font-size: 16px;}

#feedback, #termsHint {
  color: #fff;
  background-image: url('../images/warning.png');
  background-repeat: no-repeat;
  background-position: 2px 14px;
  padding: 10px 0 0 22px;}

#packageHint {
  color: #fff;
  background-image: url('../images/hint.png');
  background-repeat: no-repeat;
  background-position: 2px 5px;
  padding-left: 22px;}

label.selectbox {
  display: inline;}

label.checkbox {
  display: inline;
  font-size: 16px;}

/* Link to show list */
h2 a {
  font-size: 12px; }

a.show{
  font-size: 12px; 
  padding: 5px; 
  letter-spacing: 0; 
  position: relative;
  top: -5px;
  left: 10px;}

/* form example */
#newItemButton {padding: 10px 20px 75px 20px; display: none;}
#newItemForm {padding-top: 20px;}
#itemDescription {width: 360px;}
#newItemForm input[type='submit'] {margin-top: 0; text-align: left;}
#showForm, #add {
	
	cursor: pointer;
}

/* Attributes example */
#group {
  margin: 10px;
  border: 2px solid #fff;}

/* Events object */
.date, li i {
  font-size: 12px;
  padding-left: 8px;}


/* Additional styles for position example */
#slideAd {
  width: 130px;
  height: 60px;
  background-color: #403c3b;
  background-image: url('../images/adverlion.png');
  background-repeat: no-repeat;
  background-position: 10px center;
  color: #fff;
  border-top: 1px solid #fff;
  border-left: 1px solid #fff;
  border-bottom: 1px solid #fff;
  padding: 25px 20px 10px 85px;
  position: fixed;
  bottom: 20px;
  right: -235px;
  text-transform: uppercase;}

#footer {
  background:none;
  color: #fff;}

/* Small screen:mobile */
@media only screen and (max-width: 500px) {
  body {
      background-color: #403c3b;
  }
  #page {
    max-width: 480px;
  }
}
@media only screen and (min-width: 501px) and (max-width: 767px) {
  #page {
    max-width: 480px;
    margin: 20px auto 20px auto;
  }
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
  #page {
    max-width: 480px;
    margin: 20px auto 20px auto;
  }
}
/* Larger screens act like a demo for the app */
@media only screen and (min-width: 960px) {
  #page {
    max-width: 480px;
    margin: 20px auto 20px auto;
  }
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { 
  h1{
    background-image: url(../images/2xkinglogo.png);
    background-size: 72px 72px;
  }
}




Javascript code

$(function() {
	
  $newItemForm = $('#newItemForm');
  $newItemButton = $('#newItemButton');
  $ulElem = $('#page ul');
  $liElems = $('#page ul li');
  $showForm = $('#showForm');
  $itemDescription = $('#itemDescription');
  $counter = $('#counter');
  
  /* if I put $liElemsNotComplete inside of the function updateCounter instead of
   * $('#page ul  li[class!=complete]'), I get 4 forever as the length of the li elements 
   * On the other hand, $('#page ul  li[class!=complete]').length returns the number of lis (5, 6, 7) when elements
   * are appended to the ul or removed from it.
   * 
   *  Why does this happen?
   *  
   *  $liElemsNotComplete.length (I get always 4). 
   *  $('#page ul  li[class!=complete]') (I get the correct length of the li)
   
   $liElemsNotComplete = $('#page ul  li[class!=complete]');
   
  */
  
  $liElems.each(function(index){
	  
	  $(this).hide().delay(index * 700).fadeIn(); 
  });
  
  updateCounter();
  
  $newItemForm.hide();
  $newItemButton.show();
  
  $showForm.on('click', function(){
	 
	  $newItemButton.hide(); 
	  $newItemForm.show();
	  $itemDescription.focus();
  });
  
  $newItemForm.on('submit', function(event) {
	  
      event.preventDefault();
      
      var itemDescription = $itemDescription.val();
      var newLi = '<li>' + itemDescription + '</li>';
      
      $ulElem.append(newLi);
      
      $itemDescription.val('');
      
      updateCounter();
  
  });
  
  $liElems.on('click', function() {
	 
	  var $currLiElem =  $(this).detach();
	  $currLiElem.attr('class', 'complete');
	  $('#page ul li:last').after($currLiElem);
	  
	  $currLiElem.on('click', function() {
		  
		  $(this).remove();
		  
		  updateCounter();
	  });
  });

  function updateCounter()
  {
	// var numOfLis = $liElemsNotComplete.length;
	var numOfLis = $('#page ul li[class!=complete]').length;
	$counter.text(numOfLis);
  }
});




Is This A Good Question/Topic? 0
  • +

Replies To: Length of Lis is always four

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4128
  • View blog
  • Posts: 13,023
  • Joined: 08-June 10

Re: Length of Lis is always four

Posted 07 June 2017 - 06:36 AM

The reason is that jQuery object lists are not live (in contrast to NodeLists as returned natively by JS) and hence when you use the variable, you use the same collection that you requested the first time not what the DOM currently contains.
Was This Post Helpful? 0
  • +
  • -

#3 au.ceif.  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 25-April 17

Re: Length of Lis is always four

Posted 07 June 2017 - 08:36 AM

Quote

and hence when you use the variable, you use the same collection that you requested the first time not what the DOM currently contains.


Then, how would I get what the DOM currently contains with respect to the lists?
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4128
  • View blog
  • Posts: 13,023
  • Joined: 08-June 10

Re: Length of Lis is always four

Posted 07 June 2017 - 10:53 PM

You would need to re-fetch the elements each time.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1