Javascript dollar sign variable not working

I have the following code in my Wordpress:

(function ($) {
  var $header = $("div.header");

  $(window).bind("scroll resize", function () {
    if ($(window).scrollTop() > 30) {
      $("div.header").stop().animate({
        'opacity': 0.24
      }, {
        duration: 1000
      });
    } else {
      $header.stop().animate({
        'opacity': 1
      }, {
        duration: 1000
      });
    }
  });
})(jQuery);

If the statement starts when it is supposed, but never ...

BUT

If I enclose it with:

jQuery(document).ready(function($) {        
  // code here
});

Things are good. Why?

thank

+5
source share
1 answer

Maybe you are trying to use jQuery when dom in not build. Try using the function $(document).ready:

(function ($) {
  $(document).ready(function () {
    $header = $("div.header");
    $header.remove();
  });
})(jQuery);

About what you asked in the question:

jQuery(document).ready(function ($) {
  // code
});

It works because it does the same thing: it binds an event handler readyand passes the jQueryobject as a parameter to the function as $.

Now what did you do before:

(function ($) {
  $header = $("div.header");
  $header.remove();
})(jQuery);

Here you simply declare an anonymous function with the name $:

function ($) {
}

jQuery , $:

(function ($) {
})(jQuery);
+9

All Articles