-2

I can't set up an Eventlistener and somehow my function doesn't work. Can someone please help me fix that and explain what i did wrong ? Thank you

const backwardsButton = document.getElementById("backwards-button");
const container = document.getElementById("backwards-container");
backwardsButton.addEventListener("click", backwards)
function backwards() {
    const backwardsInput = document.getElementById("backwards-input").value.split("").reverse().join("");
    container.textContent =  backwardsInput;
    console.log(backwardsInput)
}
  <input type="text" id="backwards-input">
  <button id="backwards-button">Button</button>
  <p id="backwards-container"></p>
Igor
  • 32
  • 7
  • [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Andreas Oct 26 '20 at 16:22
  • 1
    Probably: [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Andreas Oct 26 '20 at 16:24
  • I tested your script, and it worked. Maybe you have javascript errors from other js code in your page. Check in browser's console. – CoursesWeb Oct 26 '20 at 16:28

2 Answers2

0

I found the mistake i made. I placed the script tag above my all other tags and thats the reason why it doesn't work. Javascript can't find them because it seems they are not created yet. This is wrong:

<script src="script.js"></script>
<input type="text" id="backwards-input">
 <button id="backwards-button">Button</button>
 <p id="backwards-container"></p>

Always place your script tags before the body closing tag, so javascript sees every element. This is the right way to do it:

<input type="text" id="backwards-input">
  <button id="backwards-button">Button</button>
  <p id="backwards-container"></p>
<script src="script.js"></script>
Igor
  • 32
  • 7
-1

You did the addEventListener wrong, try this:

const backwardsButton = document.getElementById("backwards-button");
const container = document.getElementById("backwards-container");
backwardsButton.addEventListener("click", function(){ backwards() })
function backwards() {
    const backwardsInput = document.getElementById("backwards-input").value.split("").reverse().join("");
    container.textContent =  backwardsInput;
    console.log(backwardsInput)
}
<input type="text" id="backwards-input">
  <button id="backwards-button">Button</button>
  <p id="backwards-container"></p>
  • Hey hacker19374, i did the eventlistener right, all i did wrong was placing the script tag wrong.Thank you for your help. You might want to see my answer that i posted on my question :) Have a nice day! – Igor Oct 26 '20 at 16:41