Can not find Jquery - javascript

I have written some codes by Jquery but because of a reason, it can not find Jquery. I have changed $ to Jquery and still get the same error. What if I change that to the pure JS, any comments on that?
var listener = throttle(300, function () {
slotsAtlantic.forEach(function (item) {
var $item = jQuery('#' + item.id);
if ($item.length) {
var $parent = $item.parent();
var index = slotsAtlantic.indexOf(item);
if ($parent.is(':visible') && ((window.scrollY || window.pageYOffset) >= ($parent.offset().top - jQuery(window).height() - 300))) {
googletag.cmd.push(function () {
googletag.pubads().refresh([item.slot]);
});
slotsAtlantic.splice(index, 1);
}
}
});
});

If you are getting an error JQuery not found, it probably means that either you are not including the JQuery script or for some reason, JQuery variable is getting undefined. Can you post your whole html code? Alternately, can you ensure the inclusion of JQuery scripts? E.g. to include JQuery v1.12.0 from Google CDN, you need to have a script tag like following
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

Related

Object expected on jQuery selector

I am working on a function that changes the source of an image tag to a background-image. This function should be really helpful for the way images will look in IE. I have tried debugging, but I get stuck on an object expected error. This happens on the second line:
if ( ! Modernizr.objectfit ) {
$('.wrapper__figure').each(function () {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')');
}
});
}
The only way I can get that code to cause that error in IE is if jQuery's noConflict has been used, so $ isn't jQuery anymore (example: http://output.jsbin.com/bixijotala). If so, you probably want to use an IIFE to use a local $, passing in jQuery:
(function($) {
if ( ! Modernizr.objectfit ) {
$('.wrapper__figure').each(function () {
var $container = $(this),
imgUrl = $container.find('img').attr('src');
if (imgUrl) {
$container
.css('backgroundImage', 'url(' + imgUrl + ')');
}
});
}
})(jQuery);
Or of course, you'd get this if you don't have jQuery loaded at all, in which case the answer is: Load jQuery, prior to running that code.

Using jQuery plugins in Meteor

I have been trying to add a jQuery plugin to Meteor but Meteor refuses to let the plugin work client side.
The example is I have this plugin that allows me to shuffle a bunch of divs around called jQuery Shuffle but when I call the following script in the head or from an external file it does not execute. It could be the plugin not publishing functions but it is client side so that makes no sense. I have verified that javascript and jQuery is working through a few console.log() command tests and those seem to work in external files or in the head wether they are inclosed in a jQuery function or not. Here is the code I am trying to use with jQuery Shuffle:
(do take note that this script also is using a few other plugins that appear not to be working either)
$(document).ready(function () {
var hash = window.location.hash.substr(1);
// Puts hash into search field
if (hash !== "") {
$("#search").val(hash);
$("#search").focus();
$('#search').keyup();
}
/* initialize shuffle plugin */
var $grid = $('#grid');
var $gridn = $('#gridn');
$grid.shuffle({
itemSelector: '.item',
group: 'alll'
});
$gridn.shuffle({
itemSelector: '.item',
group: 'news'
});
/* detects a news post */
if (hash.indexOf("news") > -1) {
$('#alll').removeClass('active');
$('#news').addClass('active');
$('#n-news').addClass('active');
$grid.shuffle('shuffle', 'news');
}
/* reshuffle when user clicks a filter item */
$('#filter a').click(function (e) {
e.preventDefault();
window.scrollTo(0, 0);
// set active class
$('#filter a').removeClass('active');
$(this).addClass('active');
// get group name from clicked item
var groupName = $(this).attr('data-group');
// reshuffle grid
$grid.shuffle('shuffle', groupName);
$gridn.shuffle('shuffle', groupName);
var n_catagories = ["n-v", "n-am", "n-av", "n-gd", "n-d", "comic", "blog"];
n_catagories.forEach(function (n_selectedcat) {
if ($("#" + n_selectedcat).hasClass("active")) {
$('#news').addClass('active');
//console.log(n_selectedcat)
}
});
});
// Sorting options
$('.select-options').on('change', function () {
var sort = this.value,
opts = {};
// We're given the element wrapped in jQuery
if (sort === 'date-created') {
opts = {
reverse: true,
by: function ($el) {
return $el.data('date-created');
}
};
} else if (sort === 'title') {
opts = {
by: function ($el) {
return $el.data('title').toLowerCase();
}
};
}
// Filter elements
$grid.shuffle('sort', opts);
});
// Advanced filtering
$('.search').on('keyup change', function () {
var val = this.value.toLowerCase();
window.scrollTo(0, 0);
$grid.shuffle('shuffle', function ($el, shuffle) {
// Only search elements in the current group
if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
return false;
}
var text = $.trim($el.find('.item-tags').text()).toLowerCase() + $.trim($el.find('.hidden').text()).toLowerCase();
return text.indexOf(val) !== -1;
});
$gridn.shuffle('shuffle', function ($el, shuffle) {
// Only search elements in the current group
if (shuffle.group !== 'all' && $.inArray(shuffle.group, $el.data('groups')) === -1) {
return false;
}
var text = $.trim($el.find('.item-tags').text()).toLowerCase() + $.trim($el.find('.hidden').text()).toLowerCase();
return text.indexOf(val) !== -1;
});
});
//REMOVE AND HIDE HANDELER
var $nnitems = $('.nnotice');
$(".nnotice-button").click(function () {
Cookies.set('hidennotice', 'true', {
expires: 31557600
});
});
if (Cookies.get('hidennotice') == 'true') {
$grid.shuffle('remove', $nnitems);
}
$(".nnotice").click(function () {
$grid.shuffle('remove', $nnitems);
});
//Auto Shuffle
$(".social-toggle").click(function () {
$(".social-stuffs").slideToggle("slow");
setTimeout(function () {
var catagories = ["alll", "v", "am", "av", "gd", "d", "news", "n-v", "n-am", "n-av", "n-gd", "n-d", "comic", "blog"];
catagories.forEach(function (selectedcat) {
if ($("#" + selectedcat).hasClass("active")) {
$grid.shuffle('shuffle', selectedcat);
}
});
}, 1000);
});
});
When not enclosed in Meteor, this script works as expected.
I have tried loading the JS files for the plugins by calling them normally through <script type="text/javascript" src="directory/somescript.js"></script> and by loading the scripts through the /client directory meteor uses to process files that are going to the client. It automatically loads these files in a <script> when put here. Even with Meteor loading them it seems not to work. I don't know if it is because the functions inside the plugins need to be published or if it is just no possible to use these kinds of plugins/apis with Meteor.
This is a working, unfinished version of the site without Meteor (and that has missing files and an unfinished color scheme)
Edit:
Basically I just need to be able to load a jQuery plugin somehow and then load the script to control it. That is what I am having trouble doing.
Using plugins like query could be a little tricky on meteor, example you are using
$(document).ready(function () {});
And its ok but i prefer to work with
Meteor.startup(function () {
});
Reference here Stack Question about onReady and Startup
Also some people prefer to use the Template.myTemplate.rendered ) function(){}
and its works (on my case works), and also try to use some Timeouts
You are not getting anything errors on the console, because nothings wrong happens all DOM elements were created, i face this problems many times using Carrousels, dynamic list from codrops etc.
If you have your web/project on some github repo or working in some cloud host Service like nitrous.io i could help you
Safest way is to deliver the plugin as a package and initialise it in template.rendered
I had this problem with a jquery plugin.
My html code was:
<head>
<meta charset="utf-8">
<!-- Plugin JQuery -->
<script src="js/jquery.easing.min.js"></script>
</head>
<body>
{{main}}
</body>
Then I put the script after {{main}} template and it works. The script is loaded after all javascript meteor packages:
<head>
<meta charset="utf-8">
</head>
<body>
{{main}}
<!-- Plugin JQuery -->
<script src="js/jquery.easing.min.js"></script>
</body>

jQuery conflicting with another on one page

I'm having an issue with my jQuery noConflict. The page that I'm trying to put the jQuery on has a drop-down navigation that already uses the noConflict() rule. Can I use more then one noConlfict on a page for different animations? I will have 3 different jQuery functions running simultaneously on one page. Separately they work fine, but once added together on a page they stop working. Below is one of the jQuery's that needs to run. Can someone help me add the noConflict() rule to it?
$(function() {
var current = 1;
var iterate = function(){
var i = parseInt(current+1);
var lis = $('#rotmenu').children('li').size();
if(i>lis) i = 1;
display($('#rotmenu li:nth-child('+i+')'));
}
display($('#rotmenu li:first'));
var slidetime = setInterval(iterate,5000);
$('#rotmenu li').bind('click',function(e){
clearTimeout(slidetime);
display($(this));
e.preventDefault();
});
function display(elem){
var $this = elem;
var repeat = false;
if(current == parseInt($this.index() + 1))
repeat = true;
if(!repeat)
$this.parent().find('li:nth-child('+current+') a').stop(true,true).animate({'marginRight':'-20px'},300,function(){
$(this).animate({'opacity':'0.7'},700);
});
current = parseInt($this.index() + 1);
var elem = $('a',$this);
elem.stop(true,true).animate({'marginRight':'0px','opacity':'1.0'},300);
var info_elem = elem.next();
$('#rot1 .heading').animate({'left':'-420px'}, 500,'easeOutCirc',function(){
$('h1',$(this)).html(info_elem.find('.info_heading').html());
$(this).animate({'left':'0px'},400,'easeInOutQuad');
});
$('#rot1 .description').animate({'bottom':'-270px'},500,'easeOutCirc',function(){
$('p',$(this)).html(info_elem.find('.info_description').html());
$(this).animate({'bottom':'0px'},400,'easeInOutQuad');
})
$('#rot1').prepend(
$('<img/>',{
style : 'opacity:0',
className : 'bg'
}).load(
function(){
$(this).animate({'opacity':'1'},600);
$('#rot1 img:first').next().animate({'opacity':'0'},700,function(){
$(this).remove();
});
}
).attr('src', info_elem.find('.info_image').html())
);
}
});
As #adaneo already commented, you always should wrap you code into the jQuery method but after that you even should call noConflict with the first parameter true:
$.noConflict(true);
This removes your jQuery completely from the jQuery and $ variable and returns a jQuery object. You can use that return value to use it in your code by giving it to your object or method as parameter:
function MyFunction($) {
$(doSomeThing);
}
MyFunction($.noConflict(true));

Why does this function no longer work in jquery 1.9.1?

I've decided to update all my jquery to work with jquery 1.9.1 but I can find out why this script has stopped working. Works fine in all other jquery versions.
// Typewriter function
$.fn.Typewriter = function Typewriter(opts) {
var $this = this,
defaults = {
animDelay: 50
},
settings = $.extend(defaults, opts);
var objDiv = document.getElementById(settings.div);
$.each(settings.text, function (i, letter) {
setTimeout(function () {
$this.html($this.html() + (letter != '\n' ? letter : '<br />'));
objDiv.scrollTop = objDiv.scrollHeight;
}, settings.animDelay * i);
});
};
// Call with
// $('#divID').Typewriter({animDelay: 10,text: 'text to animate', div: 'divID'});
$('#outputDiv').Typewriter({
animDelay: 10,
text: 'Why does this not work in jquery 1.9.1? :( ',
div: 'outputDiv'
});
Js fiddle included below
http://jsfiddle.net/T2AJ5/
EDIT:
Using the chrome development tool I get a error in the console reading:
Uncaught TypeError: Cannot use 'in' operator to search for '42' in Why
does this not work in jquery 1.9.1? :(
One does not use $.each to loop over strings. I doubt it worked properly before. For a quick fix, change it to settings.text.split('').
Btw, appending to innerHTML can be troublesome. Better use the DOM, see here for that callback hell wrapped in a jQuery plugin :-)

ASP.NET WebForms Checking all Checkboxes in a GridView using jQuery v1.9.0 doesn't work

I've a problem with my application regarding jQuery. I tried a code example ( https://web.archive.org/web/20210513220745/http://aspnet.4guysfromrolla.com/articles/120810-1.aspx ) to use a Header CheckBox to check/uncheck all rows inside a GridView. The sample code works with jQuery v1.4.4 but doesn't work with the latest jQuery release v1.9.0.
Here's the code.
<script type="text/javascript">
var allCheckBoxSelector = '#<%=gvFileList.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=gvFileList.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
With jQuery v1.4.4 everything works perfect. Using jQuery v1.9.0 every page load I get a "Object doesn't support this property or method: .live" error. If I use the syntax:
$(allCheckBoxSelector).click(function () {...
instead of the one above, I avoid the error but the Header Checkbox works only once. If I click it again nothing appens.
I also tried the .on syntax:
$(allCheckBoxSelector).on('click', function () {...
but it doesn't work too.
I'd like to know if that issue is due to a change or a bug in jQuery v1.9.0.
jQuery live should now be replaced by on. If the code worked before it should just work after you change live by on.
I got to the bottom of the problem: had to use .prop instead of .attr. I made some small modifications in the code too.
Here's a working demo on JS Bin: http://jsbin.com/egopar/4/edit
Here's the working code for jQuery 1.9:
$(document).ready(function () {
var allCheckBoxSelector = $('#chkAll');
var checkBoxSelector = $('input:checkbox:not(#chkAll)');
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
//console.log(allCheckboxesAreChecked);
$(allCheckBoxSelector).prop('checked', allCheckboxesAreChecked);
}
$(allCheckBoxSelector).on('click', function () {
$(checkBoxSelector).prop('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).on('click', function () {
ToggleCheckUncheckAllOptionAsNeeded();
});
});
If you are not using jQuery anywhere else in your page, you can use a very simple javascript to do this. There are many ways to do this, but this works for me and can be attached to buttons, links, etc. checkid is the client id and select being true or false.
function checktoggle(checkid,select){
var check=document.getElementById(checkid);
var numinput=check.getElementsByTagName('input');
for (i=0; i<numinput.length; i++){
numinput[i].checked=select;
}
}
Solved!
Thanks to Leniel Macaferi suggestions I used .on and .prop methods instead of .live and .attr but I make a different implementation of the script that finally works with jQuery v1.9.0 on my application.
<script type="text/javascript">
var allCheckBoxSelector = '#<%=gvFileList.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=gvFileList.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded()
{
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).prop('checked', allCheckboxesAreChecked);
}
$(document).ready(function()
{
$(allCheckBoxSelector).on('click', function()
{
$(checkBoxSelector).prop('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).on('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>

Categories