I have 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 statement kicks in when supposed but else never...
BUT
If I enclose it with:
jQuery(document).ready(function($) {
// code here
});
It's all fine. Why?
Thank you
I have 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 statement kicks in when supposed but else never...
BUT
If I enclose it with:
jQuery(document).ready(function($) {
// code here
});
It's all fine. Why?
Thank you
Share Improve this question edited Sep 5, 2012 at 4:49 Danil Speransky 30.5k6 gold badges69 silver badges78 bronze badges asked Sep 5, 2012 at 4:16 daniel.tosabadaniel.tosaba 2,5639 gold badges36 silver badges47 bronze badges 11- What is the javascript error occuring or provide your wordpress url containing error so we can answer correctly. – Harsh Baid Commented Sep 5, 2012 at 4:18
- 1 "Why doesn't it work??" is not an error message that I'm familiar with. – Explosion Pills Commented Sep 5, 2012 at 4:18
- 2 @ExplosionPills: it's like "the sky is blue" and "water is wet" and "gravity is a downer" and "friction is a drag". true, but useless. – Marc B Commented Sep 5, 2012 at 4:20
- I've just edited my code. Hope it is all demystified now. I am not getting any JS errors reported in Chrome. – daniel.tosaba Commented Sep 5, 2012 at 4:21
-
2
As others have pointed out, in one case (
$header = ..
), the DOM is being accessed (though the jQuery element selector) before it is ready .. there are plenty of duplicates on this. The event fires sometime after the DOM is ready. – user166390 Commented Sep 5, 2012 at 4:35
1 Answer
Reset to default 13May be you're trying to use jQuery when dom in not build. Try to use $(document).ready
function:
(function ($) {
$(document).ready(function () {
$header = $("div.header");
$header.remove();
});
})(jQuery);
About what you have mantioned in the question:
jQuery(document).ready(function ($) {
// code
});
It works because it do the same thing: it binds event handler on ready
event and pass jQuery
object as a parameter to the function as $
.
Now what you did before:
(function ($) {
$header = $("div.header");
$header.remove();
})(jQuery);
Here you just declare anonymous function with named $
parameter:
function ($) {
}
And call it with jQuery
object as a parameter, which will be available in the function as $
:
(function ($) {
})(jQuery);