0

I am trying to use regular javaScript to create an event listener, when this is clicked, a function is called and data is passed with it. The function gets the data and returns it in an alert. In my code below, the function and alert fires on page load, not when clicked as desired.

<button data-id="777" id="dataClicker">Load Data</button>
<span id="response"></span>
<script>
var dataElement = document.getElementById('dataClicker');
dataElement.addEventListener('click', myFunction(dataElement));
function myFunction(dataElement) {
    var dataId = dataElement.getAttribute('data-id');
    alert(dataId);
}
</script>

I guess the more specific question is how to write something like this that is done in jQuery so easily in plain vanilla javaScript?

<div class="photos">
    <img src="/img/cakes/1.jpg" alt="Patisserie JuJu" width="800" height="800" />
    <img src="/img/cakes/2.jpg" alt="Patisserie JuJu" width="800" height="800" />
    <img src="/img/cakes/3.jpg" alt="Patisserie JuJu" width="800" height="800" />
</div>

$(document).ready(function(){
    $('.photos img').click(function(){
        window.open($(this).attr('src'));
    });
});
drooh
  • 762
  • 2
  • 15
  • 36

2 Answers2

4

You call myFunction and pass its return value to addEventlistener rather than passing myFunction itself. Fixed:

<button data-id="777" id="dataClicker">Load Data</button>
<span id="response"></span>
<script>
var dataElement = document.getElementById('dataClicker');
dataElement.addEventListener('click', () => myFunction(dataElement));
function myFunction(dataElement) {
    var dataId = dataElement.getAttribute('data-id');
    alert(dataId);
}
</script>
Mohrn
  • 793
  • 4
  • 14
  • Can you explain the ()=> part ? – drooh Aug 08 '19 at 20:15
  • You can write it as `function () { myFunction(dataElement) }` if that makes more sense to you. I'm declaring a function that will be called by the eventListener (on the click event). Whatever function you pass as the second argument to `addEventListener` will be called. Note that `myFunction(dataElement)` is NOT a function, it's `undefined`, because `myFunction(dataElement)` means _evaluate the function `myFunction` with the parameter `dataElement`_. And the evaluation of that is `undefined` (`myFunction` doesn't return anything) – Mohrn Aug 08 '19 at 20:31
  • @drooh That's an ES6 arrow function, basically a short way of writing `function() { return myFunction(dataElement) }`. – Fabian von Ellerts Aug 08 '19 at 20:31
1

In your example you don't even need the parameter because dataElement is already defined:

var dataElement = document.getElementById('dataClicker');

dataElement.addEventListener('click', myFunction);

function myFunction() {
    var dataId = dataElement.getAttribute('data-id');
    alert(dataId);
}

Note that I call ('click', myFunction) instead of ('click', myFunction()) as @Mohrn explains.

Fabian von Ellerts
  • 3,261
  • 28
  • 31