Build a Palindrome Checker Project - Build a Palindrome Checker

Tell us what’s happening:

there is a evertlistener on my “checkbutton”, but nothing would happen when i click it .

Your code so far

<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset = "utf-8">
    <title>Palindrome Checker</title>
    <link rel = "stylesheet" href = "styles.css">
    
  </head>
  <body>
    <h1>Palindrome Checker</h1>
    <input id = "text-input" type="text">
    <button id = "check-btn" >Check</button>
    <div id = "result"></div>

    <script src = "script.js"></script>
  </body>
</html>
/* file: styles.css */

/* file: script.js */
//初始化变量
const userInput = document.getElementById("text-input");
const checkBtn = document.getElementById("check-btn");
const result = document.getElementById("result");


//定义基础函数
function isPalindrome(str){
  const strReverse = str.replace(/[^A-Za-z0-9]/gi, '').split('').reverse().join('');
  return str == strReverse ? true : false;
}

const outputResult = (input) => {
  if(isPalindrome(input)){
    result.innerHTML = `${input} is a palindrome`
  }else{
    result.innerHTML = `${input} is not a palindrome`
  }
}


//设置事件侦听
checkBtn.addEventListener('click', outputResult(userInput.value));

outputResult(userInput.value);


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0

Challenge Information:

Build a Palindrome Checker Project - Build a Palindrome Checker

This event listener is not being provided with a callback function. What you are providing here is whatever the returned result is of calling outputResult (which i am guessing is not a function).

Instead, provide a reference to the event handler so take away the parenthesis and arguments.

1 Like

Hi there,

The second argument for addEventListener must be a callback function.
While in your case, outputResult(userInput.value) is a function call.

To make this work, you should put your function call inside an anonymous function.

You can look at the example on this link as a reference:

element.addEventListener("click", function() {
  myFunction(p1, p2);
});

Thank for spending time to solve my question , it helps a lot .
now i understand the second argument which i provided in addEventListener method is actually not a function but an undifined data, and then i change it to a callback function, and it works.

1 Like