Home » Jquery » Function is not called when using vanilla javascript but works in jquery-Exceptionshub

Function is not called when using vanilla javascript but works in jquery-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to convert a jquery code to vanilla javascript code but I am not able to get the working code in vanilla js. I am not able to figure out the error. What is my mistake?

jquery

$('#refresh').click(function( event ) {
  refreshQuestion(event, $(this).data('question-id'));
})

vanilla javascript

document.addEventListener('DOMContentLoaded', () => {
  let refreshIcon = document.getElementById('refresh');
  refreshIcon.addEventListener('click', (event) => {
    // console.log('click event');
    refreshQuestion(event, event.target.dataset.questionId);
  });
});
function refreshQuestion(event, questionId) {
  event.preventDefault();
  getQuestion(questionId);
}

function getQuestion(qPos){
  $('#update').val('refresh');
  $("#question_form").submit();
};

If I use the jquery code then it works correctly but if I use vanilla javascript code then the the event is triggered only once and not the next time. If I do not call the refreshQuestion() and just do console.log('click event') then it is displayed whenever I click the button. How can I make the javascript code equivalent to jquery code?

How to&Answer: