cancel
Showing results for 
Search instead for 
Did you mean: 

document.addEventListener are not working

document.addEventListener are not working

Hello,

 

I need to use a document.addEventListener in my Javascript.

I wrote a new block and in the phtml I add the javascript ... in jsfiddle it is working, but not in Magento 2 Theme:

 

<div id="top-search-icon" onclick="toogleSearch()"></div>

<script>
var visible = 0;

function toogleSearch() {
  if (visible == 0) {
    openSearch();
    visible = 1;
  } else {
    closeSearch();
    visible = 0;
  }
}

function openSearch() {
  document.getElementById("top-search-icon").style.background = "url(https://company.com/pub/media/wysiwyg/close.png) no-repeat";
  document.getElementById("live-search").style.animation = "fade-in 1s";
  document.getElementById("live-search").style.display = "block";
}

function closeSearch() {

  document.getElementById("top-search-icon").style.background =
    "url(https://gedomo.com/pub/media/wysiwyg/search.png) no-repeat";
  document.getElementById("live-search-faded").style.animation = "fade-out 1s";
  document.getElementById("live-search-faded").style.display = "block";
}

  // We need to keep track of faded in elements so we can apply fade out later in CSS
  document.addEventListener('animationstart', function(e) {
    alert(e.target.id);
    if (e.animationName === 'fade-in') {
      e.target.id = e.target.id + '-faded';
    }
  });

  document.addEventListener('animationend', function(e) {
    if (e.animationName === 'fade-out') {
      e.target.id = e.target.id.replace('-faded', '');
      document.getElementById("live-search").style.display = "none";
    }
  });

</script>

the document.addEventListener('animationstart', function(e) { and  document.addEventListener('animationend', function(e) { are not fired.

 

 

When I click on the div, the function document.addEventListener('animationstart', function(e) { should change the id and when closing the other restore the id.

 

But I get :

TypeError: document.getElementById(...) is null

 

I checked that it´s not loading with an alert window. It is not displaying. But when I check the loaded site, I see the javascript is present.

 

In jsfidlle it works fine:

https://jsfiddle.net/sdhvntmy/

 

 

1 REPLY 1

Re: document.addEventListener are not working

This error TypeError: document.getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element. The solution is that you need to put your JavaScript code after the closure of the HTML element or more generally before < /body > tag.