enqueue hover function

I am trying to enqueue a hover function in my functios.php of my child theme, so that when hovering over a title, a div with a text will be visible. The code I am using is this:

<?php
add_action( 'wp_enqueue_scripts', 'home_game', 20);  

function home_game(){
?>
<script>
    let title1 = document.getElementById("home-title1");
    title1.addEventListener('mouseover', mouseOver);
    title1.addEventListener('mouseout', mouseOut);
    
    function mouseOver(){
    document.getElementById('title-box').style.display = 'none';
    document.getElementById('home-box1').style.display = 'block';
}
    function mouseOut(){
    document.getElementById('title-box').style.display = 'block'; 
    document.getElementById('home-box1').style.display = 'none';
}
    
</script>

<?php
}

It works in my fiddle so I guess the problem is in my php, I am fairly new with it… Any help or clue will be very appreciated!

fiddle link:
https://jsfiddle.net/rvoLc3ph/

2 Answers
2

You can add your JS to a file in your child theme /js/example.js, then enqueue it like this:

//add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
function wpdocs_theme_name_scripts() {
    wp_enqueue_script( 'script-name', get_stylesheet_directory_uri() . '/js/example.js', [], '1.0.0', true );
}

Alternatively, you can add the styles inline using this:

add_action( 'wp_enqueue_scripts', 'wpse_home_game', 20 );
function wpse_home_game() {
    wp_register_script( 'home-game', false );
    wp_enqueue_script( 'home-game' );

    $script = "

    let title1 = document.getElementById('home-title1');

    // Check if title1 was present before wiring up event listeners.
    if ( null !== title1 )  {
        title1.addEventListener('mouseover', mouseOver);
        title1.addEventListener('mouseout', mouseOut);
    }

    function mouseOver(){
        document.getElementById('title-box').style.display = 'none';
        document.getElementById('home-box1').style.display = 'block';
    }

    function mouseOut(){
        document.getElementById('title-box').style.display = 'block';
        document.getElementById('home-box1').style.display = 'none';
    }

    ";

    wp_add_inline_script( 'home-game', $script );
}

See for source of this trick from @birgire wp_add_inline_script without dependency

Leave a Comment