Corrected code based on Matthew's suggestions (event delegation)