Okay
  Public Ticket #3055854
Custom JS field not working as expected
Closed

Comments

  •  1
    studium_creative_studio started the conversation

    Hi there, 

    I've written a custom JS code to open/close my index at the bottom of the page and inserted it in 'Custom JS Code (Head)' in Salient > General Settings > CSS/Script Related. It does nothing. However, if I paste the code in a Raw JS block inside the page it works (as you can see at the moment in the URL provided). 

    I have this element in a lot of pages (but not all). It's not very good practice to place a Raw JS in each page when I could just paste it in one place. Any ideas why it isn't working?

    The code is as follows:

    <script>
    var index = document.querySelector('.index');
    var indexRow = document.querySelector('.index-row');

    indexRow.addEventListener('click', function handleClick() {
      index.classList.toggle('isOpen');
      indexRow.classList.toggle('isOpen');
    });
    </script>


    Thanks


  •  1,877
    Judith replied

    Hi There,

    Thanks for keeping in touch.

    Please allow me to escalate this to the developer to assist further.

    Thanks.

  •  1,070
    ThemeNectar replied

    Hey studium_creative_studio,

    When you place your JS in the head via the theme options, the DOM has not loaded yet and thus your querySelector's will return nothing and fail to bind the events. You can correct that by changing your snippet to wait for the document elements to load like so:

    <script>
    jQuery(document).ready(function($){
      var index = document.querySelector('.index');
      var indexRow = document.querySelector('.index-row');
      indexRow.addEventListener('click', function handleClick() {
        index.classList.toggle('isOpen');
        indexRow.classList.toggle('isOpen');
      });
    });
    </script>
    

    Kind regards,

  •  1
    studium_creative_studio replied

    Worked just fine! Thanks