简体   繁体   中英

Why is my Javascript mouseover event not working on my WordPress website?

I am trying to add a hover event listener via JavaScript on an element in my checkout page in my WordPress website. the site being hosted with Google Cloud via a vm instance. I normally have to log in via ssh if I want to make any changes to my code. The theme I am using is a child theme I made from the storefront theme, I made sure I have registered my JavaScript on to my child theme in the functions.php, I then tested my code on the google chrome devtool console and it worked fine. But it somehow doesn't work on my external JavaScript file.

Here is my functions.php code to register my script and style.

<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );

function my_theme_enqueue_styles() {
 wp_enqueue_style( 'storefront', get_template_directory_uri() 
.'/style.css' );

wp_enqueue_script('jquery');

wp_enqueue_script('gt-custom-events',get_stylesheet_directory_uri() 
. '/js/gt_custom_events.js', 'jquery', '1.0.0',true);
}

?>

gt_custom_events.js:

jQuery(document).ready(()=>{

    let placeOrder = document.getElementById('place_order');
    window.dataLayer = window.dataLayer || [];

    placeOrder.addEventListener("mouseover", (e)=>{
            alert('hover');
    });
});// end of document ready

I have also double checked with view page source, and my file is also being loaded on the page.

link to the website is: http://35.225.152.200

and I want my script to work on my checkout page.

I have previously tried putting this script on to the markup itself (embedded JavaScript). I first tried on the header and on the footer and the result was the same...

I have also tried using the ES5 version of JavaScript which didnt change the result either.

I recently also tried enqueue jQuery on to independently on top of adding it as a dependency and that did not solve my problem.

The alert is only for testing purposes but eventually I am going to push an on to the dataLayer for Google Tag manager.

You have error in your code. Here is the output from browser's console:

TypeError: place_order is null

So it means that there is no element with id equals to place_order on page. CSS selector used under the hood is #place_order .

And basically if you're using jQuery better write all code in it's syntax:

jQuery(document).ready(()=>{
    jQuery('#place_order').hover(() => {
        alert('hover');
    });
});

But it does not fix main issue outlined above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM