• Hi

    I’m trying to learn how to use javascript in wordpress and doing this by doing some really simple JS-functions. However have run into a problem when placing the script in an external file.

    (not sure if this is the correct forum, but starting here)

    in my external file, called myScript.js I have this code:

    
    function myFunction() {
      document.getElementById('demo').innerHTML = "Paragraph changed.";
    }
    

    in functions php

    
    function your_scripts() {
                        wp_register_script('myFunction', '/js/myScript.js', false);
                        // This registers your script with a name so you can call it to enqueue it
                        wp_enqueue_script( 'myFunction' );
                        // enqueuing your script ensures it will be inserted in the propoer place in the header section
                }
                add_action('wp_enqueue_scripts', 'myFunction');
    

    And in my header-php

    
    <p id="demo">A Paragraph.</p>
    <button type="button" onclick="myFunction()">Try it</button>
    

    So the myScript.js seems to be loading but when clickin the button I get the error myFunction not defined

    cannot understand what I’ve done wrong..

    • This topic was modified 5 years, 10 months ago by Jan Dembowski.
Viewing 5 replies - 1 through 5 (of 5 total)
  • By replacing the theme “header.php” file with your own, you are disrupting the WordPress page assembly flow, lots of things you expect to happen just will not get started. So reinstate your theme’s header.php file please.
    Then to get your paragraph with id=”demo” and your button, put them into the text of a page. View the page and check with your browser inspector what has been loaded.

    Thread Starter ololi01

    (@ololi01)

    Thanks for your reply! ?? However, not really sure on what u mean that I’m replacing the php-file with my own? I’m edititng the actual header.php pf the theme.

    Thread Starter ololi01

    (@ololi01)

    But your recommendation made it work ??

    Thread Starter ololi01

    (@ololi01)

    Thanks, now I just have to backtrack what happened to understand it ??

    Try using add_action('wp_enqueue_scripts', 'your_scripts');. The add_action function is expecting the callback that you are using to pass the enqueueing.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘New to javascript in wordpress’ is closed to new replies.