0

myFunction123 isnt running when its inside the other jQuery function. How do I solve it?

function myFunction123() {
  alert("Hello World!");
}

myFunction123(); // This works

document.querySelector(`#${HOME_GROUP} .what-you-can-do-btn`).addEventListener('click', () => {
  myFunction123(); // This does not
});
Shiny
  • 4,945
  • 3
  • 17
  • 33
  • 2
    Let's debug it. How can you verify that your event listener is being called? Maybe add a console.log statement inside of it? Perhaps your query selector is not finding the element. – Bryantee Jan 08 '20 at 00:16

2 Answers2

1

Something wrong with your selector.

I tried:

function myFunction123() {
   alert("Hello World!");
}

myFunction123(); // works

document.querySelector('body').addEventListener('click', () => {
   myFunction123();
});

and it works. So that means document.querySelector(#${HOME_GROUP} .what-you-can-do-btn) probably returns undefined

Try to select element by ID only like document.querySelector('#yourId')

Nik B
  • 617
  • 6
  • 11
0

First you must wait for Dom to load since you are attaching event listener to Dom objects. Then using convenient selector with jQuery attach the listener using

$({selector}) where selector can be id using {#} selector $('#id-of-element') or class using dot selector - $('.class-of-element').

If you happen to be passing a reference to a function like in the code below you do not need parenthesis since the event itself will invoke the function. e.g. [$('#hey').on('click', clickHandler)] in your case [domElement.addEventListener('click', myFunction123);]

Complete Example:

//Function that handles the event
function clickHandler(){
  console.log('hey');
}

$(document).ready(function() {

  //Id Selector using jQuery
  $('#hey').on('click', clickHandler);

  //Class Selector using jQuery
  $('.what-you-can-do-btn').on('click', clickHandler)

})
Eray Ismailov
  • 305
  • 3
  • 8