I'm trying to build a jQuery Plugin using there Name spacing as per there direction here:
http://docs.jquery.com/Plugins/Authoring#Namespacing
Now i have run into a problem my plugin need to use a setTimeout to fire one of its methods,
var jScrollerMethods = {
ready:function(){
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
this.moveLeft();
}else if(settings.direction = "right"){
this.moveRight();
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}
but as I though would happen setTimeout is fired from the Window not the plugin object and being that I want the plugin to be usable on more than once per page so I can't just save the current object to the window how can I achieve this?
I found out that when using this outside of the return this.each will give you the exact selector results
So with some work i have managed to do it,
var jScrollerMethods = {
ready:function(){
selector = this;
return this.each(function(){
var self = this,
$this = $(this),
data = $this.data('jScroller');
settings.timeoutHandle = setTimeout(function(){
if(settings.direction = "left"){
selector.jScroller("moveLeft");
}else if(settings.direction = "right"){
selector.jScroller("moveRight");
}
}, settings.time);
$this.data('jScroller', {
settings: settings,
element: this
});
});
}
$.fn.jScroller = function(call){
if ( jScrollerMethods[call] ) {
return jScrollerMethods[call].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof call === 'object' || ! call ) {
if (call) { $.extend(settings, call); }
return jScrollerMethods.init.apply( this, call );
} else {
$.error( 'Method ' + call + ' does not exist on jQuery.jScroller' );
}
}
Related
I am trying to write a jQuery method which watches for changes of inputs inside a given form element:
(function($) {
$.fn.filter = function(options) {
console.log('Outside');
var self = this;
var settings = $.extend({}, options);
this.on('change', ':input', function(e) {
console.log('Inside');
$(self).serialize(); // Here is the problem
});
return this;
}
})(jQuery);
$('#filter-form').filter();
When I use $(self).serialize();, the function being called again. I expect that the 'Outside' part only runs once on initialization and not every time the input of the form changes.
I do not understand what is happening here. I'd appreciate if someone could explain to me why this is happening!
The issue is that you are redefining jQuery's filter method, which it internally uses in its serialize method. If you change the name, it will work. The definition of serialize is shown below:
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( _i, elem ) {
var val = jQuery( this ).val();
if ( val == null ) {
return null;
}
if ( Array.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
Working Example:
(function($) {
$.fn._filter = function(options) {
console.log('Outside');
var self = this;
var settings = $.extend({}, options);
this.on('change', ':input', function(e) {
console.log('Inside');
$(self).serialize();
});
return this;
}
})(jQuery);
$('#filter-form')._filter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="filter-form">
<input type="text">
</form>
i have plugin construction like this:
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html);
});
}
};
var button = {
html: '<button class="btn">Button</button>'
};
var input = {
html: '<input type="text" class="input" value="" />'
};
var actions ={
clicked:function(){
alert('clicked');
},
hover:function(){
alert('hover');
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By clicking on add button you will add input from input.html and button from button.html. How can i initialize click event for input element and button objects from actions.clicked and hover event from actions.hover
You can define events when append button and input.Try following code i hope this helpful.
(function($){
var defaults = {
param1:null,
param2:null
};
var methods = {
init:function(params) {
var options = $.extend({}, defaults, params);
$(this).append('<button class="addbtn">Add elements</button>');
$(document).on('click','.addbtn',function(){
$('body').append(button.html+input.html)
.find(".foo")
.click(function(){actions.clicked($(this))})
.hover(function(){actions.hover($(this))})
});
}
};
var button = {
html: '<button class="btn foo">Button</button>'
};
var input = {
html: '<input type="text" class="input foo" value="" />'
};
var actions ={
clicked:function($this){
console.log($this);
},
hover:function($this){
console.log($this);
}
};
$.fn.JPlugin = function(method){
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method"' + method + '" is not found jQuery.mySimplePlugin' );
}
};
})(jQuery);
$('body').JPlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am using infinite scroll to load posts and tried to integrate a custom like button for every single posts that needs a small jquery script to work. My problem is I added this Jquery directly after the sucess in ajax load posts. But when I load eg the 3. page my jquery script executes twice and on the posts of the 2nd page the lke buttons are not working correctly. How can I handle this? If I dont execute the code after the ajax request and only call this jquery code globally the like buttons do not work in the new loaded posts of the ajax infinite scroll. Maybe I need to stop the sript of before when eg loadin 3. page through the ajax infinite scroll but how? This is my code:
function load_more_posts(selector){
var url = $(selector).attr('href');
var data;
loading = true;
$.ajax({
url: url,
data: data,
success: function( data ) {
var $items = $( '.loading-content .item', data );
$new_anchor = $( selector, data );
$items.addClass('hidden');
if ( $('#cooked-plugin-page .result-section.masonry-layout .loading-content').length ){
$( '.loading-content').isotope( 'insert', $items );
} else {
$( '.loading-content').append($items);
setTimeout(function() {
$items.removeClass('hidden');
}, 200);
}
if($new_anchor.length) {
$(selector).attr('href', $new_anchor.attr('href'));
} else {
$(selector).remove();
}
loading = false;
$('.like-btn').each(function() {
var $button = $(this),
$icon = $button.find('> i'),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id');
cookied = $button.attr('data-cookied');
userLiked = $button.attr('data-userliked');
if ( cookied == 1 && typeof likedRecipes !== 'undefined' && likedRecipes.split(',').indexOf(recipeID) > -1 || userLiked == 1 ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
}
});
$('#cooked-plugin-page .like-btn').on('click', function() {
var $button = $(this),
$icon = $button.find('> i'),
$count = $button.find('.like-count'),
count = parseInt($count.text()),
likedRecipes = $.cookie('cpLikedRecipes'),
recipeID = $button.attr('data-recipe-id'),
cookied = $button.attr('data-cookied'),
likeURL = $button.attr('href'),
likeAction;
if ( $icon.hasClass('fa-heart-o') ) {
$icon.removeClass('fa-heart-o').addClass('fa-heart');
count++;
if (cookied == 1){
if ( typeof likedRecipes === 'undefined' ) {
likedRecipes = recipeID;
} else {
likedRecipes = likedRecipes + ',' + recipeID;
}
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
}
likeAction = 'like';
} else {
$icon.removeClass('fa-heart').addClass('fa-heart-o');
count--;
if (cookied == 1){
if ( typeof likedRecipes === 'undefied' ) {
return false;
}
}
if (cookied == 1){
var likedSplit = likedRecipes.split(','),
recipeIdx = likedSplit.indexOf(recipeID);
if ( recipeIdx > -1 ) {
likedSplit.splice( recipeIdx, 1 );
likedRecipes = likedSplit.join(',');
$.cookie('cpLikedRecipes', likedRecipes, { expires: 365 } );
likeAction = 'dislike';
}
} else {
likeAction = 'dislike';
}
}
$.ajax({
'url' : likeURL,
'data': {
'action' : 'cp_like',
'likeAction': likeAction
},
success: function(data) {
$count.text(data);
}
});
return false;
});
$('#cooked-plugin-page .tab-links a').on('click', function() {
var tab = $(this).attr('href');
if ( !$(this).is('.current') ){
$(this).addClass('current').siblings('.current').removeClass('current');
$('#cooked-plugin-page.fullscreen .tab').removeClass('current');
$(tab).addClass('current');
$win.scrollTop(0);
}
return false;
});
if($('.rating-holder').length) {
$('.rating-holder .rate')
.on('mouseenter', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
$parent.addClass('rate-' + (my_index + 1));
})
.on('mouseleave', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
var rated = $parent.attr('data-rated');
$parent.removeClass(function(index, css) {
return (css.match (/(^|\s)rate-\S+/g) || []).join(' ');
});
if(rated !== undefined) {
$parent.addClass('rate-' + rated);
}
})
.on('click', function() {
var $me = $(this);
var $parent = $me.parents('.rating-holder');
var my_index = $me.index();
$('.rating-real-value').val(my_index + 1);
$parent.attr('data-rated', my_index + 1);
$parent.addClass('rate-' + (my_index + 1));
});
}
setTimeout(function() {
masonry();
}, 500);
}
});
}
There's a great plugin for scrolling. He has methods such as bund, unbind, destroy and e.t.c.:
https://github.com/infinite-scroll/infinite-scroll#methods
Here is the example.
I create an object that have 3 elements referenced by the first parameter (document.querySelectorAll...) the I loop through those elements and launch a specific scrolling function (simplified in the example. Inside this function I use this approach to detect the scroll and save perf. I pass the element every time I call this function (first commented console.log) and works well, then inside the timer also I still having the 3 elements (in this example) but then inside the if statement I only have the first one.
I think I understand the problem, but I'm not finding a solution.
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
function MyObject(el, opt){
this.el = el;
this.opt = extend( {}, this.opt );
extend( this.opt, opt );
this._init();
}
MyObject.prototype._init = function(){
var self = this;
//this.didScroll = false; //Remove this and put it per element
this.totalObjs = document.querySelectorAll(this.el);
this.objs = [].slice.call( this.totalObjs );
this.objs.forEach( function( el, i ) {
self._onScroll(el);
});
};
MyObject.prototype._onScroll = function(e){
var self = this;
e.didScroll = false; // Add per element
addEvent(window, 'scroll', function(){
e.didScroll = true;
});
// Here I have my 3 elements
// console.log(e.id);
setInterval(function() {
// Here I have my 3 elements
// console.log(e.id);
if( e.didScroll ){
e.didScroll = false;
// Here I have only the first element
console.log(e.id);
}
}, 500);
};
var obj1 = new MyObject('.obj', {});
The problem is your scope. You are setting an interval for each element but checking inside that interval from the main object and setting the didScroll variable to false on the first one. Set this variable on the element and it works just fine.
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[key] = b[key];
}
}
return a;
}
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
function MyObject(el, opt){
this.el = el;
this.opt = extend( {}, this.opt );
extend( this.opt, opt );
this._init();
}
MyObject.prototype._init = function(){
var self = this;
//this.didScroll = false; //Remove this and put it per element
this.totalObjs = document.querySelectorAll(this.el);
this.objs = [].slice.call( this.totalObjs );
this.objs.forEach( function( el, i ) {
self._onScroll(el);
});
};
MyObject.prototype._onScroll = function(e){
var self = this;
e.didScroll = false; // Add per element
addEvent(window, 'scroll', function(){
e.didScroll = true;
});
// Here I have my 3 elements
// console.log(e.id);
setInterval(function() {
// Here I have my 3 elements
// console.log(e.id);
if( e.didScroll ){
e.didScroll = false;
// Here I have only the first element
console.log(e.id);
}
}, 500);
};
var obj1 = new MyObject('.obj', {});
I got a simple plugin as below:
$.fn.ajaxSubmit = function(options){
var submisable = true;
}
I want to able to change/access the variable myvar from outside the plugin, by doing something like below:
$(function(){
$('form').ajaxSubmit();
$('div').click(function(){
submisable =false;
});
});
You can also create methods to access the variables that are inside a plug in:
$.fn.ajaxSubmit = function(options){
var submisable = true;
$.fn.ajaxSubmit.setSubmissable = function(val){
submisable = val;
}
}
Then you can call it like this.
$('form').ajaxSubmit();
$('form').ajaxSubmit.setSubmissable(false);
This solution is not straight forward, but follows the jquery plugin guidelines.
(function($) {
var myVar = "Hi";
var methods = {
init: function(option) {
return this.each(function() {
$(this).data("test", myVar);
});
},
showMessage: function() {
return this.each(function() {
alert($(this).data("test"));
});
},
setVar: function(msg) {
return this.each(function() {
$(this).data("test", msg);
});
},
doSomething: function() {
//perform your action here
}
}
$.fn.Test = function(method) {
// Method calling logic
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.Test');
}
};
})(jQuery);
$("form").Test("init");
$("#getCol").click(function() {
$("form").Test("setVar", "Hello World").Test("showMessage");
});
Are you thinking to access them as properties? Something like:
$.fn.ajaxSubmit = function(options) {
var defaults = {},
o = $.extend({}, defaults, options);
var _myvar = 'blue'
this.myvar = new function(){
return _myvar;
}
this.setmyvar = function(_input){
_myvar = _input
}
return this.each(function() {
if (_myvar == 'blue') {
alert('hi');
}
if (_myvar == 'red') {
alert('bye');
}
});
}
And set like:
this.setmyvar('red');