Skip to content

Instantly share code, notes, and snippets.

@danishiqbal4
Last active March 3, 2020 07:26
Show Gist options
  • Save danishiqbal4/6f497c36b18372d062311654552bc4f8 to your computer and use it in GitHub Desktop.
Save danishiqbal4/6f497c36b18372d062311654552bc4f8 to your computer and use it in GitHub Desktop.
A Gist for Sky Verge PHP Engineer HTML/JS file.
<!-- Below I have added comments to explain -->
<!-- Also, my new solution is in a code pen: https://codepen.io/danishiqbal4/pen/jOPLMNV -->
<html>
<head>
<script>
// If not necessary for some reason, there is no need to delay the function for 10 ms.
setTimeout(
function() {
// variable declaration missing for "todos". Not declaring a variable will set it's scope to global which is unecessary
todos = document.getElementsByTagName( 'li' );
// Again variable declaration missing for "i"
i = 0;
// Unecessary to check for the "type" of "todos" on every iteration.
// We do not need to check for the "type" as getElementsByTagName will always return an array if it finds any matching tag OR else it will return an empty array.
while ( typeof( todos.item( i ) ) == 'object' ) {
// Again variable declaration missing for "todo"
todo = todos.item( i );
// Having an event listener inside a loop is worse performance wise.
// It's better to have a single event listener for all the clicks.
todo.addEventListener( 'click', function( evt ) {
// We can use the properties of the CSS Style Declaration object to add CSS
// evt.target.style.textDecoration = 'line-through';
evt.target.style = 'text-decoration: line-through';
// The value of "i" inside the event listener that is added in a loop will always be the last value of "i" which in this example is 4.
// Alert will always print 5 as 4+1=5
alert( 'Item ' + ( i + 1 ) + ': "' + evt.target.innerText + '" is done!' );
} );
i++;
}
},
10
);
</script>
</head>
<body>
<ul id="todo-app">
<li class="todo">Walk the dog</li>
<li class="todo">Pay bills</li>
<li class="todo">Make dinner</li>
<li class="todo">Code for one hour</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment