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.
Related
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>
I am working on MVC application and I have jQuery plugin, calculating width and height of page and I am calling this from document.ready function. I am getting following error
ReferenceError: getPreventDefault is not defined MyCustomScript:1:115
Use of getPreventDefault() is deprecated. Use defaultPrevented instead. jquery-1.10.2.js:5389:0
no element found
my plugin
(function($) {
$.fn.adjustOuterStripLayout = function () {
alert("strip");
$(window).bind('load resize', function () {
var viewport_height = $(window).height();
var viewport_width = $(window).width();
var webPage_containerWidth = $('.container').width();
alert("viewport_width " + viewport_width + "container " + webPage_containerWidth);
});
};
})(jQuery);
main function
$(document).ready(function () {
alert("hello");
$(this).adjustOuterStripLayout();
});
sometime it alert and sometime it not. I have also clear browser cashed and testing this on firefox and jquery version 1.10.2
Can you try the same in 'window.onload' event instead of in 'documen.ready' ?
As, you are trying to refer the window object to get height & width. Unless its not loaded you wont get that value.
Try using code like:
$(window).load(function () {
$(this).adjustOuterStripLayout();
});
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));
I'm using jquery 1.9.1 and I'm trying to develop a plugin. The problem is that the plugin isn't working. Here's the code:
;(function($) {
$.fn.single = function() {
return this.each(function(){
// Get the instance
var element = $(this);
// Resize the "data-target" divs
element.load(function(){
changeCSS(element);
});
// Bind the method to the resize window event
$(window).bind("resize", function(){
changeCSS(element);
});
});
};
// function to resize all the "data-target" divs
function changeCSS(element) {
// Grab the screen resolution
var windowWidth = $(window).width();
var windowHeight = $(window).height();
// Count how many targets the div has
var targetsSize = $("[data-target]").size();
// Resize the parent div
$(element).css({
"width" : windowWidth,
"height": windowHeight * targetsSize
});
// Resize all the targets div
$(element + "> div[data-target]").each(function(){
$(this).css({
"width" : windowWidth,
"height": windowHeight
});
});
}
})(jQuery);
And I'm calling it on the document like that:
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/single-0.1.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#single").single();
});
</script>
There's no problem in the console. What I'm doing wrong?
I'm assuming that it is because you are misusing the method .load. If you look at the jQuery docs, it is intended for:
.load() : Load data from the server and place the returned HTML
into the matched element.
http://api.jquery.com/load/
Remove the lines element.load(function ..., simply call your changeCSS function, you're already loading this extension on Document.Ready
return this.each(function () {
// ...
changeCSS(element); // <-- just run the function right away
// ... etc
});
Generally it is bad practice to call a function before it is declared. To get your plugin right, you will be better of starting structuring it correctly from the beginning. Besides that, as #mcpDESIGNS point out, you are using the .load method wrongly. Also, it would be useful if you explain what exactly it is you are trying to accomplice here.
To get a good start making jQuery plugins, try to look at the documentation at jQuery here or you can look at this tutorial.
This is the preferred structure:
(function($) {
// Declare your methods at the beginning of your plugin
var yourMethods = {
'methodOne' : function() {
},
'methodTwo' : function() {
}
};
$.fn.pluginName = function() {
return this.each(function() {
});
}
}(jQuery));
Instead of:
element.load(function(){
changeCSS(element);
});
I did:
changeCSS(element);
And... Instead of:
$(element + "> div[data-target]")
I did:
$(element).children('div[data-target]')
And now the plugin is being executed with no bugs or errors.
Thanks Guys!
I wrote code first without using functions to prototype, and of course, it worked fine:
$(function() {
$(".PortfolioFade img")
.mouseover(function() {
popup('PORTFOLIO');
var src = $(this).attr("src").replace("images/paperclip.png", "images/paperclip-black.png");
/*var src = $(this).attr("src").match(/[^\.]+/) + "-black.png";*/
$(this).attr("src", src);
})
.mouseout(function() {
;
/*var src = $(this).attr("src").replace("images/paperclip-black.png", "images/paperclip.png");
$(this).attr("src", src); Look at popup.js mouseover events*/
});
});
However, when I expressed the same in function form, the function call didn't seem to work.
$(document).ready(function() {
// put all your jQuery goodness in here.
$('body').hide().fadeIn(1000);
function ImageRollover(image_element, popup_name, original, replacement)
{
$(element)
.mouseover(function(){
popup(popup_name);
var src = $(this).attr("src").replace(original,replacement);
$(this).attr("src",src);
})
.mouseout(function(){
;
});
}
ImageRollover(".Portfolio img",'PORTFOLIO',"images/paperclip.png","images/paperclip-black.png");
});
Defining the function elsewhere didn't seem to have any effect either.
Is this what you are trying to achieve?
function ImageRollover(element, popup, original, replacement)
{
$(element).mouseover(function(){
//popup(element);
//var src = $(this).attr("src").replace(original,replacement);
$(this).attr("src",replacement);
})
.mouseout(function(){
$(this).attr("src",original);
});
}
http://jsfiddle.net/SqyDg/
Your function is defining the first variable as image_element, but you're referring to it as just element in the code. That's quite likely one factor to it not working.
You'll likely also encounter an issue with the keyword this inside your function. It isn't referring to the same object as in the original code (which jQuery sets to the HTML element for you). In your function, it is likely not being set to anything thus it's a link to window.
function ImageRollover(image_element, popup_name, original, replacement)
{
$(element)
Where element is defined?
May be you mean:
function ImageRollover(image_element, popup_name, original, replacement)
{
$(image_element)