简体   繁体   中英

jQuery in Wordpress plugin

I am making a wordpress plugin and in it I use jQuery, but it is not working.
My code is below :
script.js :

$(document).ready(function(){

    $(window).scroll(function() {

    if($(this).scrollTop() != 0) {
        $("#toTop").fadeIn("slow");    
    }

    else {
        $("#toTop").fadeOut("slow");
    }

  });

  $("#toTop").click(function() {
    $("body,html").animate({scrollTop:0},1000);

  });

});

The dollar sign is reserved in WordPress for the Prototype library, so use jQuery instead of $

jQuery(document).ready(function(){

    jQuery(window).scroll(function() {

    if(jQuery(this).scrollTop() != 0) {
        jQuery("#toTop").fadeIn("slow");    
    }

    else {
        jQuery("#toTop").fadeOut("slow");
    }

  });

  jQuery("#toTop").click(function() {
    jQuery("body,html").animate({scrollTop:0},1000);

  });

});

When you are working with jQuery and php together, you should use jQuery $no.conflict(). your code will look like this:

jQuery(document).ready(function($){

    jQuery(window).scroll(function() {

    if(jQuery(this).scrollTop() != 0) {
        jQuery("#toTop").fadeIn("slow");    
    }

    else {
        jQuery("#toTop").fadeOut("slow");
    }

  });

  jQuery("#toTop").click(function() {
    jQuery("body,html").animate({scrollTop:0},1000);

  });

});

Use jQuery like this:--

jQuery(document).ready(function($){

    $(window).scroll(function() {

        if($(this).scrollTop() != 0) {
            $("#toTop").fadeIn("slow");
        } else {
            $("#toTop").fadeOut("slow");
        }
    });

    $("#toTop").click(function() {

        $("body,html").animate({scrollTop:0},1000);

    });
});

Hope it may work.

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