javascript dollar sign variable not working - javascript

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

May 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);

Related

Conflict in using multiple JQUERY libraries

In my web application, I have a datepicker jquery, Everything works well, until I added a new jquery codes referencing a diffrent library. This Jquery's purpose is to fixate a gridview header.
After I added this code, the datepicker stopped working. What could be causing the conflict?
Here are the codes
1. DatePicker JQuery locatred in external JS File
$(function () {
$("#txtdatefrom").datepicker();
});
$(function () {
$("#txtdateto").datepicker();
});
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
}
function init() {
$(function () {
$("#txtdatefrom").datepicker();
});
$(function () {
$("#txtdateto").datepicker();
});
}
$(function () { // DOM ready
init();
});
3. Jquery to fix gridview header.
After adding this the the datepicker feature stopped working.
<script type = "text/javascript">
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
}
function init() {
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$(function () { // DOM ready
init();
});
</script>
upon checking the browser console to locate the error, here is the reason:
jquery-ui-1.8.19.custom.min.js:5 Uncaught TypeError: Cannot read property 'ui' of undefined
The issue is due to conflict in definition of init() function. In both the files, you have used the same name. Try renaming one of them and your issue should be fixed.
Edit: Try changing the second snippet to the following:
<script type = "text/javascript">
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
fixGridHeader();
}
function fixGridHeader() {
$(document).ready(function () {
$('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$(function () { // DOM ready
fixGridHeader();
});
</script>
I already found the answer. Based on research, using multiple Jquery codes or libraries can be done by using jquery.noConflict() code.
javascript for Datepicker
var $152 = jQuery.noConflict();
$152(function () {
$152("#txtdatefrom").datepicker({
changeMonth: true,
changeYear: true
});
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
$152(function () {
$152("#txtdatefrom").datepicker({
changeMonth: true,
changeYear: true
});
});
}
});
};
for gridview header
var $151 = jQuery.noConflict();
//not needed kasi it produced double scrolls, pero pwede din e.. ewan
$151(document).ready(function () {
$151('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
window.onload = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
function endRequestHandler(sender, args) {
init();
//fixGridHeader();
}
function init() {
//function fixGridHeader()
$151(document).ready(function () {
$151('#<%=grdWSR.ClientID %>').Scrollable({
ScrollHeight: 300
});
})
}
$151(function () { // DOM ready
//fixGridHeader()
init()
});
just create a variable that will be assigned with a jquery.noconflict() function. then replace all $ with the created variable per javascript. then it will work already.
reference: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

Why can't I call this jQuery function?

I need some help understanding some jQuery basics. I have a really simple function here but I can't call it.
<script type="text/javascript">
jQuery(function ($) {
callFunc();
}
function callFunc(){
alert("Function Called!");
}
);
</script>
If I don't put the alert in it's own function it triggers the alert. When I wrap it in a function and give it a name and try to call it, it doesn't work. Please help, I've been looking all over for some straightforward ways of just creating and calling jQuery functions. I've tried passing in the $ as a parameter but no matter what I try, I can't seem to just create a simple function and call it. What am I doing wrong and how do I call my function?
because of syntax error:
Your code:
jQuery(function ($) {
callFunc();
} //missing a closing ) for the JQuery(
function callFunc(){
alert("Function Called!");
}
); //extra )
Correct code:
jQuery(function ($) {
callFunc();
});
function callFunc() {
alert("Function Called!");
}
DEMO: http://jsfiddle.net/tnhswf11/
If you want to have the function inside the jQuery:
jQuery(function ($) {
function callFunc() {
alert("Function Called!");
}
callFunc();
});
DEMO: http://jsfiddle.net/tnhswf11/1/
You have syntax error
Correct syntax:
jQuery(function ($) {
callFunc();
function callFunc(){
alert("Function Called!");
}
});
or:
jQuery(function ($) {
callFunc();
});
function callFunc(){
alert("Function Called!");
}
Just a reminder. jQuery(function ($) {}); is a short hand for jQuery(document).ready(function($){});

jQuery onclick function: Undefined is not a function

Edit: I guess part of this is an issue of me being inexperienced with Drupal. I added a javascript file to site.info, so that it will be added to every page. This is all the file contains:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
When the site loads, it gets compiled into this larger script, which looks like this in the debugger:
(function ($) {
Drupal.behaviors.titlebar = {
init: function(context, settings) {
// Using percentage font size to easily increase/decrease page font size
var baseFontSize = 100;
$('.pgc-font-size a').click(function() {
if($(this).hasClass('increase')) {
if(baseFontSize < 150)
baseFontSize += 20;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
} else {
if(baseFontSize > 70)
baseFontSize -= 10;
$('.pg-content-body p').css('font-size', baseFontSize+'%');
}
});
// Print button
$('.pgc-print a').click(function() {
window.print();
})
}
};
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.titlebar.init();
});;
(function ($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function(){
if($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
// There's a problem with our jQuery loading before the ingested site's
// jQuery which is causing jQuery plugins to break (the "once" plugin in this case).
// I'm using this workaround for now
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
;
You can see my little script at the bottom there. It says there's something wrong with the first line, but I'm not sure what the problem is. What change would I need to make to my javascript file to make sure it compiles right?
I'm probably overlooking a really simple type, but I can't see what's wrong with my jQuery.
This is the part that's not working:
(function ($){
$("#ctl00_btnSearch001").on("click", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.website.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);
I have jQuery on my site, I know I do because this it's used earlier in the code with no problem. The error is showing in the debugger on the first line, '$("#ct100_btnSearch001").on("click", function(){ '. Here is a larger section of the script page:
(function($) {
Drupal.behaviors.giftTypes = {
init: function() {
// Gift details accordion
$('.pg-gift-details .accordion-items').css('display', 'none');
$('.pg-gift-details .accordion-switch').click(function() {
if ($(this).hasClass('open')) {
$(this).find('span').removeClass('icon-arrow-up').addClass('icon-arrow-down');
$('.pg-gift-details .accordion-items').slideUp('slow');
$(this).html($(this).html().replace('Hide', 'Show More'));
$(this).removeClass('open');
} else {
$(this).find('span').removeClass('icon-arrow-down').addClass('icon-arrow-up');
$('.pg-gift-details .accordion-items').slideDown('slow');
$(this).html($(this).html().replace('Show More', 'Hide'));
$(this).addClass('open');
}
})
}
}
}(jQuery));
jQuery(function() {
Drupal.behaviors.giftTypes.init();
});;
(function($) {
$("#ctl00_btnSearch001").on("click", function() {
var searchVal = $("#ctl00_txtSearch").val();
alert(searchVal);
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);;
Try to install jQuery update Module.
If you are using Drupal 6, you are not be able to use on function.
One option is to include your custom version of jQuery in your page.tpl.php, another option (not recommended) is to use live, but now is deprecated.
You can bind a function to an event use two way:
1.use bind() method and the event name as the first argument
$( "#foo" ).bind( "click", function() {
alert( "User clicked on 'foo.'" );
});
or
2.just use the event method
$( "#foo" ).click( function() {
alert( "User clicked on 'foo.'" );
});
The problem of your code is that there isn't a on event.
ref http://api.jquery.com/category/events/mouse-events/
If ctl00_btnSearch001 is a correct id for what ever you are trying to click. Try changing it to this:
(function ($){
$(document).on("click", "#ctl00_btnSearch001", function(){
var searchVal = $("#ctl00_txtSearch").val();
window.location.href = "http://www.mywebsite.org/search/?sa=Search&q=" + searchVal;
});
})(jQuery);

Angular ng-animate using javascript not working as expected

I tried to implement the demo example using JS but something went wrong with ng-switch ... I can see that new elements are being added in the dom, but ng-switch is not removing the unwanted DIVs. can you pls help ...
Here is the Fiddle...
var ngModule = angular.module('myApp', []);
ngModule.animation('js-wave-enter', function () {
return {
setup: function (element) {
//prepare the element for animation
element.css({ 'position': 'absolute', 'left': '100%' });
},
start: function (element, done, memo) {
//start the animation
element.animate({ 'left': 0 }, function () {
//call when the animation is complete
done();
});
}
}
});
ngModule.animation('js-wave-leave', function () {
return {
setup: function (element) {
//prepare the element for animation
element.css({'position': 'absolute', 'left': 0 });
},
start: function (element, done, memo) {
//start the animation
element.animate({ 'left': '-100%' }, function () {
//call when the animation is complete
done();
});
}
}
});
jQLite does not include the animate() method. You need to include jQuery proper before you include Angular and your code will work fine. So just add the following before the script tag that includes AngularJS:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
Updated jsFiddle

How do I "do stuff" at the end of this crazy jQuery animation loop without errors?

I am trying to "do some stuff" at the end of this crazy animation loop... The alert I have commented out at the end of the animation works great... However, what I really need it to do is remove/hide the closest div with a class of .item (something like this)
var jremove = $(this).closest('.item').hide();
$container.masonry('remove', jremove );
//Then trigger a reload function for masonry
reloadMasonry(); // not working yet
When I try do do anything but alert a simple message I get an error like this:
Uncaught TypeError: Object #<HTMLImageElement> has no method 'closest'
You can see it at the bottom of the animation below:
jQuery(function ($) {
$("body").on("click", ".clip_it", function () {
if ($(this).parent().find(".clip_it").length<1){
$(this).after('<a class="clip_it" href="javascript:void(0)" onclick="">CLIP IT!</a><img src="http://img.photobucket.com/albums/v29/wormholes201/animated-scissors.gif" class="ToBeAnimated">');
}
animationLoop($(this).closest(".item-inner").eq(0),$(this).parent().find(".ToBeAnimated").eq(0));
});
});
function animationLoop(ctx,ctx2) {
ctx2.fadeIn();
ctx2.css({
top: (0 - parseInt(ctx2.height()) / 2),
left: (0 - parseInt(ctx2.width()) / 2),
position:"absolute",
"z-index":800
}).rotate(270);
ctx2.animate({
top: ctx.height() - ctx2.height() / 2
}, 1000, function () {
ctx2.animate({
rotate: "180deg"
}, 1000, function () {
ctx2.animate({
left: ctx.width() - ctx2.width() / 2
}, 1000, function () {
ctx2.animate({
rotate: "90deg"
}, function () {
ctx2.animate({
top: 0-ctx2.height() / 2
}, 1000, function () {
ctx2.animate({
rotate: "0deg"
}, function () {
ctx2.animate({
left: (0 - parseInt(ctx2.width()) / 2)
}, 1000, function () {
setTimeout(animationLoop(ctx,ctx2), 1000);
//I want to remove the coupon (.item) & reload masonry here
// TEST ALERT WORKS = alert("animation complete");
var jremove = $(this).closest('.item').hide();
$container.masonry('remove', jremove );
reloadMasonry();
return false;
});
});
});
});
});
});
});
}
I am open to other suggestions if you think there is a better way? THANKS FOR HELPING!
Uncaught TypeError: Object #<HTMLImageElement> has no method 'closest'
The problem is that $ outside of your ready handler (the function you're passing into jQuery(function($) { ... });) is not pointing to jQuery, it's pointing to something else (my guess would be Prototype or MooTools). So $(this) returns an HTMLImageElement (probably enhanced by Prototype or MooTools) rather than a jQuery object, and so it has no closest function.
Either move the animationLoop function into your ready handler (so it sees the $ that jQuery passes into the ready handler instead of the global), or use jQuery instead of $ in that function.

Categories

Resources