Home » Javascript » javascript issue calling function after adding event listener

javascript issue calling function after adding event listener

Posted by: admin August 19, 2018 Leave a comment


I am working on a wikipedia viewer (https://codepen.io/rwiens/pen/YLMwBa) which is almost done but I have 2 problems:

  1. I cannot submit my search results when I press enter. I have added an event listener and can console.log “hello: but I cannot call the searchWiki function.

  2. When I do a new search the results are appended to the bottom pf my old results.

I’ve searched the web for the last half day and am stuck. Any help would be appreciated.

 <div class="container">
    <div class="banner text-center align-items">
        <h1>Wiki Search</h1>
        <p>Search for articles on Wikipedia</p>
    <form action="" class="text-center">
        <input type="search" id="search-box" placeholder="Search Here">
        <div class="buttons">
            <input type="button" onclick="searchWiki()" id="search- 
             button" value="Search">
            <input type="submit" value="Feel Lucky?">
    <div class="articles">
        <ul id="results">


 <script type="test/javascript">

    const searchBox = document.getElementById('search-box');
    const sButton = document.getElementById('search-button');
    const results = document.getElementById('results');

    window.onload = function() {

    const searchWiki = () => {
        const keyword = searchBox.value;
     &origin=*&action=opensearch&search=" + keyword + "&limit=5", {
     method: "POST",
     headers: {
       "Content-Type": "application/json"
     body: JSON.stringify({ query: event.currentTarget.value })
      .then(response => response.json())
      .then((data) => {

    const build = (data) => {
      let title = data[1];
      let description = data[2];
      let url = data[3];
    for(let x = 0; x < 5; x++){
        const item = `<a href="${url[x]}" target="#">
        results.insertAdjacentHTML("beforeend", item);


     searchBox.addEventListener("keyup", function(event) {
     if (event.key === "Enter") {