Site logo

[Resolved] Trouble inserting custom javascript into generatepress website

Home Forums Support [Resolved] Trouble inserting custom javascript into generatepress website

Home Forums Support Trouble inserting custom javascript into generatepress website

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1955792
    Benjamin

    Hi Team,

    I have created a website where I want custom javascript to be applied to the front page.

    So I followed David’s instruction here to create a hook and insert JS code in to wp_head.

    However when I navigate to my website The javascript code appears not in <head></head> but in the body. Please advise on how to get this custom JS code to be in <head> as the hook suppose to do.

    #1955815
    David
    Staff
    Customer Support

    Hi there,

    you need to wrap your Javascript in <script> tags:

    <script>
    Your Javascript here
    </script>
    #1956992
    Benjamin

    When I put the js code between the tag <script></script> the code will appear in the header when I inspect in the browser. However I couldn’t reference html element from JS. So I made a simple html and JS just to test:

    
        <div>
            <input type="text" id="lname" name="lname">
        </div>
    

    For JS code I insert into the hook element
    Hook: wp_head
    Location: Front Page

    
    <script>
    	document.getElementById("lname").value = "My Value";
    </script>
    

    However when I publish the page and look it up in the browser the input tag wasn’t populated with “My Value”. When I inspect the code via browser there is an error:

    Uncaught TypeError: Cannot set properties of null (setting ‘value’)

    May I know how can I reference html element like input tags from JS?

    #1956995
    David
    Staff
    Customer Support

    For that kind of use – you will require the script to fired after the HTML has been rendered.
    So change the Hook from wp_head to wp_footer

    #1957017
    Benjamin

    It works thanks David!

    #1957280
    David
    Staff
    Customer Support

    Glad to hear that!

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.