mdmb
mdmb

Reputation: 5283

Including typed.js in wordpress

I have been trying to add a typed.js plugin to one of the wordpress themes.

I put the typed.js in the "js" folder in the theme folder. Then I edited the functions.php in the theme folder and added:

function typed_script_init() {
    wp_enqueue_script( 'typedJS', get_template_directory_uri() . '/js/typed.js');
}

add_action('wp_enqueue_scripts', 'typed_script_init');

add_action('wp_enqueue_scripts', 'typed_init_in_footer');

function typed_init_in_footer() {
        add_action('print_footer_scripts', 'typed_init');
    }
function typed_init() { ?>
    <script type="text/javascript">
            $(function(){
                $("#typed").typed({
                    strings: ["Are you Interested?"],
                    typeSpeed: 20
                });
            });
    </script>
<?php }

I do have in one of my section in the theme:

<h1>
    <span id="typed"></span>
</h1>

And when I launch my wordpress page it does not work. I have been sitting on this for almost 3hours reading online tutorials about including javascript in wordpress and still nothing.

Is there anybody who can help me? Thanks guys!

Upvotes: 0

Views: 1678

Answers (1)

rnevius
rnevius

Reputation: 27092

The proper way to do this would be to (1) include jQuery as a dependency (you haven't mentioned if you've included jQuery), (2) use noConflict wrappers:

function typed_script_init() {
    wp_enqueue_script( 'typedJS', get_template_directory_uri() . '/js/typed.js', array('jquery') );
}
add_action('wp_enqueue_scripts', 'typed_script_init');

function typed_init() {
    echo '<script type="text/javascript">
            (function($){
              // The `$` jQuery shortcut is now available to you
              $(function(){
                $("#typed").typed({
                  strings: ["Are you Interested?"],
                  typeSpeed: 20
                });
              });
            })(jQuery);
          </script>';
}
add_action('wp_footer', 'typed_init');

I've added the scripts to the wp_footer action hook...but it may be preferable to put those scripts in an external JS file, and also enqueue them in wp_enqueue_scripts, with typedJS as a dependency.

Upvotes: 3

Related Questions