Custom jQuery-function not working on WordPress even though other loaded jQuery functions are working

I’m using WordPress 3.8.1. I want to use this function to use sticky header

<script>
$(document).ready(function() {
    var $header = $("header"),
        $clone = $header.before($header.clone().addClass("clone"));

    $(window).on("scroll", function() {
        var fromTop = $(window).scrollTop();
        console.log(fromTop);
        $("body").toggleClass("down", (fromTop > 200));
    });
});        
</script>

But it is not working for me and I don’t know why. I know that jQuery is shared to my WordPress because Flexslider 2 is now working fine.

Related posts

Leave a Reply

3 comments

  1. Add this:

    var j = jQuery.noConflict();
    

    Now you can write your jQuery code like this:

    j(document).ready(function(){
        j('.class').event(function(){
    
          // your action............
    
        });
      });
    

    Just assign the noConflict() function to a variable, and use that variable instead of $ seen in jQuery code.

  2. Late to the party here, but the correct solution to this is:

    Understand that in WordPress, jQuery is loaded in no conflict mode. This means that the $ variable is not referencing jQuery.

    But, by modifying your script to use a no-conflict-safe document ready, you can use the $ within the function.

    Modify your script as follows:

    // original code - doesn't work, because $ is not jQuery in WordPress
    // $(document).ready(function() {
    // shorthand no-conflict-safe document ready:
    jQuery(function($) {
        // Now $ is safe to use - it references jQuery within this doc ready function
        var $header = $("header"),
            $clone = $header.before($header.clone().addClass("clone"));
    
        $(window).on("scroll", function() {
            var fromTop = $(window).scrollTop();
            console.log(fromTop);
            $("body").toggleClass("down", (fromTop > 200));
        });
    });        
    
  3. Have you tried setting the jquery file in your header (assuming you have the jquery file in your templates folder, but it can be anywhere, as long as you reference it correctly):

    <script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/jquery-1.3.2.min.js"></script>
    

    Example

    $(document).ready(function(){
         $("#container").alert("blah");
         $(".goodshelf_ul li:first").css("border-top: none;");
         $(".custom_ul li:first").addClass("first");
         $("#footer .frame:last").css("margin: 0;");
         $("#footer .frame:last").addClass("last");
    });
    

    I use jquery on all my wordpress sites and it works fine
    hope this helps.