Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138249

Javascript addEventListener Callback logic

$
0
0

I am following a Javascript video tutorial in which we are learning about event- listeners. We coded the following small web app that lets you input elements on a list:

var button = document.getElementById("enter");
var input = document.getElementById("userinput");
var ul = document.querySelector("ul");

//Apparently if it is just one parameter it just gets transferred
function inputLength()
{
    return input.value.length;
}

//If there is just one parameter it gets transferred
function createListElement()
{
    var li = document.createListElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);
    input.value = "";
}

// Making sure that it does not add empty strings
function addListAfterClick()
{
    if(inputLength() > 0)
    {
        createListElement();
    }
}

//Making sure that it just adds after pressing enter
function addListAfterKeypress(event)
{
    if(inputLength() > 0 && event.keyCode === 13)
    {
        createListElement();
    }
}

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);

I am confused on why the functions were called this way:

button.addEventListener("click", addListAfterClick);
input.addEventListener("keypress", addListAfterKeypress);

Instead of this way:

button.addEventListener("click", addListAfterClick());
input.addEventListener("keypress", addListAfterKeypress(event));

I know that it has something to do with callback functions. However, I am still unsure of how it just automatically gets the values of the parameters just like of art of magic.


Viewing all articles
Browse latest Browse all 138249

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>