vkosyj vkosyj - 18 days ago 7
jQuery Question

JS function seems like does not get called

I have a array with only one element(eventually I will expand the array for sure). At the very beginning, the element in the array is popped out, then the program finds that the element matches with "F2", then a ball shows up. However, the ball does not shows up. I am concerned about my js code since I sort of use js and JQuery together. Even though I can consider JQuery as the library of the JS, I am not sure if it is the issue here. The way that I debug js code is to throw a bunch of alert() and try to find to which line alert() does not get called so I know there is a problem, but once again, I am not sure if it is the best to do it since there is no IDE in js. Totally a newbie for js. Hope someone could help me out.



$(document).ready(function() {
var notes = ["F2"];
if($('#' + notes.pop()).innerHTML == 'F2') {
$('#F2').addClass('shown')
} else {
$('#F2').removeClass('shown');
}

});

#F2{
width: 10px;
height: 10px;
background: #ccc;
border: 2px solid #ccc;
border-radius: 50%;
}

.not_shown {
display: none;
}

.shown {
display: block;
}

<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="code.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="code_js.js"></script>
</head>
<body>
<div id = "ball">
<div id = "F2" class = "not_shown"></div>
</div>
</body>
</html>




Answer

I see few issues in the code.

First $('#' + notes.pop()).innerHTML is not correct. it should be $('#' + notes.pop()).html().

Second there is not text F2 in the div. So ($('#' + notes.pop()).html() == 'F2') will fail always.

I modified it slightly.

#F2 {
  width: 10px;
  height: 10px;
  background: #ccc;
  border: 2px solid #ccc;
  border-radius: 50%;
}
.not_shown {
  display: none;
}
.shown {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <link type="text/css" rel="stylesheet" href="code.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
  <script type="text/javascript" src="code_js.js"></script>
</head>

<body>
  <div id="ball">
    <div id="F2" class="not_shown">F2</div>
  </div>
</body>

</html>
<script>
  $(document).ready(function() {
    var notes = ["F2"];
    debugger;
    if ($('#' + notes.pop()).html() == 'F2') {
      $('#F2').addClass('shown')
    } else {
      $('#F2').removeClass('shown');
    }

  });
</script>