Error on jQuery Plugin - javascript

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!

Related

Javascript function is not working sometimes at certain level

I have this Javascript function for hover items. İt has to work under 958px but its not working. so how can I control that.
But when I resize page up and down, JS stops working.
What's wrong with my function? I am unable to figure it out.
$(document).ready(() => {
if ($(window).width() >958){
$('#group-subscription .owl-item').on('mouseenter', function(){
$(this).nextAll().addClass('has-positive-translate')
$(this).prevAll().addClass('has-negative-translate')
}).on('mouseleave', function() {
removeHasClasses()
})
function removeHasClasses() {
$('#group-subscription .owl-item').removeClass('has-negative-translate has-positive-translate slider-hover-bigger')
}
}
})
Your code is not related to resizing event, it only one time execute when a page is loaded and it is ready, All in all, you should use resize event instead of the ready event.
$(window).on('resize', function(){
var winx = $(this);
if (winx.height() >= 958) {
/* use your code here */
}
});

Defer inline jQuery Ready/Bind functions

I have some legacy jQuery executing in the page that can't be moved i.e.
jQuery(document).bind('click', function(){
console.log('click');
});
Now that loading of jQuery is at the bottom of the page 'AFTER' the above inline code, the page errors 'jQuery is undefined'
I would like to use a pattern similar to this:
var deferInlineScripts = [];
window.$ = function(inlineFunction) {
deferInlineScripts.push(inlineFunction);
};
Seen working here: https://jsfiddle.net/xpvt214o/165864/
that takes the inline scripts and executes them (Once jQuery is loaded') using
for (i = 0; i < deferInlineScripts.length; i++) {
deferInlineScripts[i]();
}
But unlike the Fiddle my legacy code doesn't have the $(function(){}); and can't be moved, changed or have anything wrapped around it i.e
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
Here is the Fiddle https://jsfiddle.net/xpvt214o/165972/ that I would like to fix so the the Bind & Ready functions execute after jQuery is loaded.
Initially define window.jQuery as a function that returns a Proxy. This proxy will allow subsequent arbitrary psuedo-propery lookups (such as .bind in jQuery(document).bind) to be performed. The properties accessed and the arguments the resulting function is eventually called with can be stored in an array and then executed once jQuery is properly loaded.
<script>
const deferCallHandler = {
get: function(jqFirstArg, jqProp) {
return function(...secondArgs) {
deferredInlineScripts.push({
jqFirstArg,
jqProp,
secondArgs,
});
}
}
};
const deferredInlineScripts = [];
window.jQuery = function(jqFirstArg) {
return new Proxy(jqFirstArg, deferCallHandler);
}
document.addEventListener('DOMContentLoaded', function(){
// window.jQuery has now been properly assigned to the true jQuery object
deferredInlineScripts.forEach(({ jqFirstArg, jqProp, secondArgs }) => {
jQuery(jqFirstArg)[jqProp](...secondArgs);
});
});
/* Can't change this code */
jQuery(document).bind('click', function(){
console.log('click');
});
jQuery(document).ready(function(){
console.log('ready');
});
</script>
<div>some element</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Calling jQuery plugin from document.ready throw getPreventDefault error

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();
});

using $(this) inside jquery plugin

Here is my plugin code below.
$.fn.myplugin = function(options) {
var defaults = {
my_data_title11:"",
my_div:".getslow",
}
var settings = $.extend({}, defaults, options);
return this.each(function(){
console.log(options.my_data_title);
});
}
I am calling this plugin from an external page like this...
$('#o_vari,#0_var2').myplugin({
my_data_title11:$(this).attr("id"),my_div:'.getfast'
});
but it is displaying undefined. I am aware my_data_title11:$(this).attr("id") is not recognizing $(this) the calling statement, I even tried putting this exteral variable , but still the same problem.
From the way you have written the code, I'm assuming you wants to print o_vari and 0_var2... but that is not the case because in the context in which you have used $(this).att('id'), this does not refer to the o_varx element.
So if you want the desired output try
$('#o_vari,#0_var2').each(function () {
$(this).myplugin({
my_data_title: this.id,
my_div: '.getfast'
});
})
Demo: Fiddle

Using .style.opacity = using javascript is not working for some reason

I'm new to javascript and jquery and I am trying to make a video's opacity change when I mouseover a li item. I know 'onmouseover' works because I have tested using the same jquery I use to scroll to the top of the page onclick.
The problem seems to be the syntax to check and update the style of the video div is not working. I adapted the code from a lesson on codeacademy and don't see why it work:
window.onload = function () {
// Get the array of the li elements
var vidlink = document.getElementsByClassName('video');
// Get the iframe
var framecss = document.getElementsByClassName('videoplayer1');
// Loop through LI ELEMENTS
for (var i = 0; i < vidlink.length; i++) {
// mouseover function:
vidlink[i].onmouseover = function () {
//this doesn't work:
if (framecss.style.opacity === "0.1") {
framecss.style.opacity = "0.5";
}
};
//onclick function to scroll to the top when clicked:
vidlink[i].onclick = function () {
$("html, body").animate({
scrollTop: 0
}, 600);
};
}
};
Here is a jsfiddle you can see the html and css:
http://jsfiddle.net/m00sh00/CsyJY/11/
It seems like such a simple problem so I'm sorry if I'm missing something obvious.
Any help is much appreciated
Try this:
vidlink[i].onmouseover = function () {
if (framecss[0].style.opacity === "0.1") {
framecss[0].style.opacity = "0.5";
}
};
Or alternatively:
var framecss = document.getElementsByClassName('videoplayer1')[0];
Or, better, give the iframe an id and use document.getElementById().
The getElementsByClassName() function returns a list, not a single element. The list doesn't have a style property. In your case you know the list should have one item in it, which you access via the [0] index.
Or, given that you are using jQuery, you could rewrite it something like this:
$(document).ready(function(){
// Get the iframe
var $framecss = $('.videoplayer1');
$('.video').on({
mouseover: function () {
if ($framecss.css('opacity') < 0.15) {
$framecss.css('opacity', 0.5);
}
},
click: function () {
$("html, body").animate({
scrollTop: 0
}, 600);
}
});
});
Note that I'm testing if the opacity is less than 0.15 because when I tried it out in your fiddle it was returned as 0.10000000149011612 rather than 0.1.
Also, note that the code in your fiddle didn't run, because by default jsfiddle puts your JS in an onload handler (this can be changed from the drop-down on the left) and you then wrapped your code in window.onload = as well. And you hadn't selected jQuery from the other drop-down so .animate() wouldn't work.
Here's an updated fiddle: http://jsfiddle.net/CsyJY/23/

Categories