How can i use plugins options in javascript instanciation? - javascript

I am making a plugin on fixed nav using javascript/jQuery. Now the problem is to using defaults value. My questions are:
How can I use defaults through instantiation?
What is the easiest way to get the default values ?
;(function($){
'use strict'
$.fn.retrivenav = function(options){
var defaults = {
menuTransform : 'primary',
speed : '1000',
responsive : true
},
options = $.extend(defaults, options);
var R = function(){
this.w = $(window).width();
this.t = $('.retrivenav').offset().top;
}
var r = new R();
r.prototype.fixednav = function() {
$(window).on('scroll', function(){
});
}
}
})(jQuery);

use this keyword inside function
;(function($){
'use strict'
$.fn.retrivenav = function(options){
this.defaults = {
menuTransform : 'primary',
speed : '1000',
responsive : true
};
var options = $.extend(this.defaults, options);
var R = function(){
this.w = $(window).width();
this.t = $('.retrivenav').offset().top;
}
var r = new R();
r.prototype.fixednav = function(){
$(window).on('scroll', function(){
});
}
return this;
}
})(jQuery);
so you can use like this
var retrivenavObj = $('selector').retrivenav();
retrivenavObj.defaults;

In general:
;(function($, window, document, undefined) {
//Plugin definition
$.fn.pluginName = function(options) {
return this.each(function() {
var that = $(this);
//Get defaults
var def = $.extend({}, $.fn.pluginName.defaults, options);
var optionOne = def.optionOne;
var optionTwo = def.optionTwo;
// Here you can use optionOne, optionTwo or whatever default variable you set
});
};
//Defaults
$.fn.tableFix.defaults = {
optionOne: true,
optionTwo: false
};
})(jQuery, window, document)
Then, when you instantiate:
Defaul options
$('#affected-table').tableFix();
The plugin will get the default options (optionOne: true, optionTwo: false)
Change an option
var options = {
optionOne: false
}
$('element_to_affect').pluginName(options);
The optionOne will now be overwritten and become 'false', but optionTwo will remain false
For more information on plugin development
take a look stackoverflow

Related

Isotope - NoLayoutMode with search filtering - combining JQuery

I am trying to use the combination filters & search, with the nolayoutMode. I am not proficient in JQuery at all, so I could use some help combining the necessary code. I need the search, filter, and no layout.
It would not let me post all the code, so I linked above. Any help is appreciated.
nolayoutMode JQuery:
Isotope.Item.prototype._create = function() {
// assign id, used for original-order sorting
this.id = this.layout.itemGUID++;
// transition objects
this._transn = {
ingProperties: {},
clean: {},
onEnd: {}
};
this.sortData = {};
};
Isotope.Item.prototype.layoutPosition = function() {
this.emitEvent("layout", [this]);
};
Isotope.prototype.arrange = function(opts) {
// set any options pass
this.option(opts);
this._getIsInstant();
// just filter
this.filteredItems = this._filter(this.items);
// flag for initalized
this._isLayoutInited = true;
};
// layout mode that does not position items
Isotope.LayoutMode.create("none");
// --------------- //
// init Isotope
var $grid = $(".grid").isotope({
itemSelector: ".element-item",
layoutMode: "none"
});
// filter functions
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this)
.find(".number")
.text();
return parseInt(number, 10) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this)
.find(".name")
.text();
return name.match(/ium$/);
}
};
// bind filter button click
$("#filters").on("click", "button", function() {
var filterValue = $(this).attr("data-filter");
// use filterFn if matches value
filterValue = filterFns[filterValue] || filterValue;
$grid.isotope({ filter: filterValue });
});
// change is-checked class on buttons
$(".button-group").each(function(i, buttonGroup) {
var $buttonGroup = $(buttonGroup);
$buttonGroup.on("click", "button", function() {
$buttonGroup.find(".is-checked").removeClass("is-checked");
$(this).addClass("is-checked");
});
});

OnePage Navbar detecting section IDs above target

I am having trouble with my website's navigation bar.
It is supposed to detect and highlight the navigation link when the user has reached the Section ID. However, it seems to be detecting the section well above their target.
How would I get the navigation bar to accurately detect the sections?
Just in case, here's the jQuery smooth-scrolling code:
;(function($, window, document, undefined){
// our plugin constructor
var OnePageNav = function(elem, options){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
this.metadata = this.$elem.data('plugin-options');
this.$win = $(window);
this.sections = {};
this.didScroll = false;
this.$doc = $(document);
this.docHeight = this.$doc.height();
};
// the plugin prototype
OnePageNav.prototype = {
defaults: {
navItems: 'a',
currentClass: 'current',
changeHash: false,
easing: 'swing',
filter: '',
scrollSpeed: 750,
scrollThreshold: 0.5,
begin: false,
end: false,
scrollChange: false
},
init: function() {
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options, this.metadata);
this.$nav = this.$elem.find(this.config.navItems);
//Filter any links out of the nav
if(this.config.filter !== '') {
this.$nav = this.$nav.filter(this.config.filter);
}
//Handle clicks on the nav
this.$nav.on('click.onePageNav', $.proxy(this.handleClick, this));
//Get the section positions
this.getPositions();
//Handle scroll changes
this.bindInterval();
//Update the positions on resize too
this.$win.on('resize.onePageNav', $.proxy(this.getPositions, this));
return this;
},
adjustNav: function(self, $parent) {
self.$elem.find('.' + self.config.currentClass).removeClass(self.config.currentClass);
$parent.addClass(self.config.currentClass);
},
bindInterval: function() {
var self = this;
var docHeight;
self.$win.on('scroll.onePageNav', function() {
self.didScroll = true;
});
self.t = setInterval(function() {
docHeight = self.$doc.height();
//If it was scrolled
if(self.didScroll) {
self.didScroll = false;
self.scrollChange();
}
//If the document height changes
if(docHeight !== self.docHeight) {
self.docHeight = docHeight;
self.getPositions();
}
}, 250);
},
getHash: function($link) {
return $link.attr('href').split('#')[1];
},
getPositions: function() {
var self = this;
var linkHref;
var topPos;
var $target;
self.$nav.each(function() {
linkHref = self.getHash($(this));
$target = $('#' + linkHref);
if($target.length) {
topPos = $target.offset().top;
self.sections[linkHref] = Math.round(topPos);
}
});
},
getSection: function(windowPos) {
var returnValue = null;
var windowHeight = Math.round(this.$win.height() * this.config.scrollThreshold);
for(var section in this.sections) {
if((this.sections[section] - windowHeight) < windowPos) {
returnValue = section;
}
}
return returnValue;
},
handleClick: function(e) {
var self = this;
var $link = $(e.currentTarget);
var $parent = $link.parent();
var newLoc = '#' + self.getHash($link);
if(!$parent.hasClass(self.config.currentClass)) {
//Start callback
if(self.config.begin) {
self.config.begin();
}
//Change the highlighted nav item
self.adjustNav(self, $parent);
//Removing the auto-adjust on scroll
self.unbindInterval();
//Scroll to the correct position
self.scrollTo(newLoc, function() {
//Do we need to change the hash?
if(self.config.changeHash) {
window.location.hash = newLoc;
}
//Add the auto-adjust on scroll back in
self.bindInterval();
//End callback
if(self.config.end) {
self.config.end();
}
});
}
e.preventDefault();
},
scrollChange: function() {
var windowTop = this.$win.scrollTop();
var position = this.getSection(windowTop);
var $parent;
//If the position is set
if(position !== null) {
$parent = this.$elem.find('a[href$="#' + position + '"]').parent();
//If it's not already the current section
if(!$parent.hasClass(this.config.currentClass)) {
//Change the highlighted nav item
this.adjustNav(this, $parent);
//If there is a scrollChange callback
if(this.config.scrollChange) {
this.config.scrollChange($parent);
}
}
}
},
scrollTo: function(target, callback) {
var offset = $(target).offset().top;
$('html, body').animate({
scrollTop: offset
}, this.config.scrollSpeed, this.config.easing, callback);
},
unbindInterval: function() {
clearInterval(this.t);
this.$win.unbind('scroll.onePageNav');
}
};
OnePageNav.defaults = OnePageNav.prototype.defaults;
$.fn.onePageNav = function(options) {
return this.each(function() {
new OnePageNav(this, options).init();
});
};
})( jQuery, window , document );

jquery plugin, reference video element in DOM

I have started jQuery plugin where I want to retrieve the .duration and .currentTime on a HTML5 video, from within a bound .on('click', ) event.
I am struggling to capture this information within my plugin.registerClick function, here is my code:
(function ($) {
$.myPlugin = function (element, options) {
var defaults = {
videoOnPage: 0,
dataSource: 'data/jsonIntervals.txt',
registerClick: function () { }
}
var plugin = this;
plugin.settings = {}
var $element = $(element);
element = element;
plugin.init = function () {
plugin.settings = $.extend({}, defaults, options);
$element.on('click', plugin.registerClick);
getJsonIntervals();
}
plugin.registerClick = function () {
var duration = $('video').get(plugin.settings.videoOnPage).duration;
console.log('duration: ' + duration);
}
var startTimes = [];
var dataSet = false;
var getJsonIntervals = function () {
if (dataSet == false) {
//calls a $.getJSON method.
//populates startTimes
//updates dataSet = true;
};
}
plugin.init();
}
$.fn.myPlugin = function (options) {
return this.each(function () {
if (undefined == $(this).data('myPlugin')) {
var plugin = new $.myPlugin(this, options);
$(this).data('myPlugin', plugin);
}
})
};
})(jQuery);
$(function () {
$('#button1').myPlugin();
});
Here my sample jsFiddle Click Here
Seems to work for me:
plugin.registerClick = function () {
var video = $('video').get(0);
console.log('duration: ' + video.duration);
console.log('currenttime: ' + video.currentTime);
}
http://jsfiddle.net/p4w040uz/2/
You need to play the video first then click the button. The browser has to retrieve the meta data first before it can return it.
Additional reference material you can read up:
http://www.w3schools.com/tags/av_event_loadedmetadata.asp
http://www.w3.org/2010/05/video/mediaevents.html

Strange data binding issue

I have a crazy issue with my code. I'm trying to implement this jsfiddle code
In my code, but I have no success. Here is what I have done:
ViewModel:
viewModelInbox = function(){
query: ko.observable('');
var checked = false,
mainData = ko.observableArray([]),
showView = ko.observable(),
currentView = ko.observable(),
approve = function(){
},
disapprove = function(){},
toggle = function () {
if(checked){
$.each(mainData(), function(){
this.checkB(false);
});
checked = false;
return;
}
if(!checked){
$.each(mainData(), function(){
this.checkB(true);
});
checked = true;
return;
}
};
viewModelInbox.mainData = ko.dependentObservable(function() {
var search = this.query().toLowerCase();
return ko.utils.arrayFilter(viewModelInbox, function(test) {
return test.name.toLowerCase().indexOf(search) >= 0;
});
}, viewModelInbox);
return {
mainData: mainData,
showView: showView,
currentView: currentView,
approve: approve,
disapprove: disapprove,
toggle: toggle
};
},
The mainData observable array is holding some values as name, code, date, etc.
The issue I have is that I'm getting this error:
TypeError: this.query is not a function
var search = this.query().toLowerCase();
I'm pretty sure that I'm missing something really small, but as I'm a total noob in knockoutjs I can not spot it.
It seems not something small.
Your view model should be either
var ViewModel = function() {
this.query = ko.observable(''); // use ';'
this.mainData = ko.observableArray([]);
};
or
var viewModel = {
query: ko.observable(''), // use ','
mainData: ko.observableArray([])
};
You can't mix them.
Or you can write like this:
var ViewModelInbox = function() {
var self = this;
self.query = ko.observable('');
self.dataSource = []; // data source
self.mainData = ko.computed(function() {
var search = self.query().toLowerCase();
return ko.utils.arrayFilter(self.dataSource, function(item) {
return item.name.toLowerCase().indexOf(search) >= 0;
});
});
self.showView = ko.observable();
self.currentView = ko.observable();
self.approve = function() {
};
self.disapprove = function() {
};
self.checked = ko.observable(true);
self.toggle = function() {
var toCheck = !self.checked();
ko.arrayForEach(self.mainData(), function(data) {
data.checkB(toCheck);
});
self.checked(toCheck);
};
};
ko.applyBindings(new ViewModelInbox());

Knockout js foreach grid not working

Here is the fiddle: http://jsfiddle.net/7RDc3/2096/
The 'Add Service' button doesn't work. I need it to mirror the functionality of the 'Add Hardware' button.
Something is wrong with my code below: You can see it in action on the fiddle above though.
var viewModel = function(hardware, services) {
var self = this;
self.hardwares = ko.observableArray(hardware);
self.services = ko.observableArray(services);
self.addHardware = function() {
self.hardwares.push({
name: "",
price: ""
});
};
self.removeHardware = function(hardware) {
self.hardwares.remove(hardware);
};
self.addService = function() {
self.services.push({
name: "",
price: ""
});
};
self.removeService = function(services) {
self.services.remove(services);
};
self.save = function(form) {
var allModel = [];
ko.utils.arrayForEach(services(), function (service) {
allOrders.push(ko.toJS(service));
});
ko.utils.arrayForEach(hardwares(), function (hardware) {
allOrders.push(ko.toJS(hardware));
});
alert("Could now transmit to server: " + ko.utils.stringifyJson(allOrders));
};
};
var FinalViewModel = new viewModel([]);
ko.applyBindings(FinalViewModel);
You're not passing an argument in for the services parameter when you construct the viewmodel:
var FinalViewModel = new viewModel([], []);
ko.applyBindings(FinalViewModel);
Updated fiddle: http://jsfiddle.net/7RDc3/2097/
You could also augment your constructor to use empty arrays if an argument isn't supplied:
var viewModel = function(hardware, services) {
var self = this;
self.hardwares = ko.observableArray(hardware || []);
self.services = ko.observableArray(services || []);
/* snip */
};

Categories