简体   繁体   中英

Fixing a JavaScript conflict in Wordpress, help using wp_enqueue_script

I think (not 100% sure) that I am suffering from a javascript conflict. I am using a pluggin to generate a countdown clock on my WordPress page, and I am using some simple custom made javascript with jQuery to make a div appear and dissapear on the page at certain points of scrolling.

To make the appearing / dissapearing div work correctly I added two javascript calls into my header:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/test1.js"></script> 

The first being the jquery library and the second being my custom script. After adding these lines of code to the header, the countdown clock stopped working on my website. Through a little debugging I have realized that it is the Google hosted script that is causing the clock not too work.

When I have the code for the Google hosted jquery library in my header I receive the following error: Error = Object [object Object] has no method 'jCountdown'

I believe the solution to this is using the wp_enqueue_script and wp_register_script in the functions.php file to add the two .js files I need, and removing the code from the header. However, I am un familiar with how these bits of code work and can not seem to figure it out. Below is the code I believe needs to be used in the functions.php file, but I have been unsuccessful in making it work.

function notSureWhatGoesHere() {
        wp_register_script(notSureWhatGoesHere);
        wp_enqueue_script(notSureWhatGoesHere);
        }

        add_action(notSureWhatGoesHere);

And here is a link to my test webpage: http://jltest.biz/test-1

Thank you so much for your help and time.

You have a Error = Object [object Object] has no method 'jCountdown'

Maybe your plugin hasn't loaded properly...

Remove the jQuery you added jQuery.1.10.2 so i am not supprised that it doesn't work..

PLUS - WordPress has already added a version of jQuery.1.8.3

Now, in your test file you have this

var startY = 840;
var stopY = 1900;

$(window).scroll(function(){
    checkY();
});

function checkY()
{
    console.log($(window).scrollTop()); 
    if($(window).scrollTop() > startY && $(window).scrollTop() <= stopY)
    {
        console.log("Show"); 

        $('.fixedDiv').fadeIn("slow"); 
    }
    else
    {
        console.log("Hide"); 
        $('.fixedDiv').fadeOut();
    }
}

checkY();

Wordpress uses jQuery.noConflict(); by default so you need to make sure you wrap your code in something like the following

(function( $ ) {

    // Code Here....

}( jQuery ));

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