How do I subclass the TextCellEditor of Slickgrid?
I want to style the editors used in slickgrid using the uniform library; to do so I need to call
$("input, textarea, select, button").uniform();
after the html is generated; in other words after the editor object's init function is called; Currently I just copy the entire editor source code and add that line just before the end of the init function. I just seems non elegant.
edit:
to be clear to people unfamiliar with slickgrid, here is the code:
var myTextCellEditor = function(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function() {
$input = $("<INPUT type=text class='editor-text' />")
.appendTo(args.container)
.bind("keydown.nav", function(e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
})
.focus()
.select();
$input.uniform();
};
this.destroy = function() {
$input.remove();
};
this.focus = function() {
$input.focus();
};
this.loadValue = function(item) {
defaultValue = item[args.column.field] || "";
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function() {
return $input.val();
};
this.applyValue = function(item,state) {
item[args.column.field] = state;
};
this.isValueChanged = function() {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function() {
if (args.column.validator) {
var validationResults = args.column.validator($input.val());
if (!validationResults.valid)
return validationResults;
}
return {
valid: true,
msg: null
};
};
this.init();
}
Where $input.uniform(); is the only line that is different from the default TextCellEditor.
You could bind a .ready() event to the generated html content by class using .live() so it applies to all future content, not just content present in the initial DOM.
So...
$('.classOfSlickGrid').live('ready', function() {
$("input, textarea, select, button").uniform();
}
Related
I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()
on my website I have a div .toggle-search that if you click on it it expands to .search-expand where a search form is. This is the code in jQuery
/* Toggle header search
/* ------------------------------------ */
$('.toggle-search').click(function(){
$('.toggle-search').toggleClass('active');
$('.search-expand').fadeToggle(250);
setTimeout(function(){
$('.search-expand input').focus();
}, 300);
});
Now the only way to close the .search-expand is to click once again on the .toggle-search. But I want to change that it closes if you click anywhere else on the site. For an easier example I have the Hueman theme, and I'm talking about the top right corner search option. http://demo.alxmedia.se/hueman/
Thanks!
Add the event on all elements except the search area.
$('body *:not(".search-expand")').click(function(){
$('.toggle-search').removeClass('active');
$('.search-expand').fadeOut(250);
});
or another way,
$('body').click(function(e){
if(e.target.className.indexOf('search-expand') < 0){
$('.toggle-search').removeClass('active');
$('.search-expand').fadeOut(250);
}
});
var isSearchFieldOpen = false;
var $toggleSearch = $('.toggle-search');
var $searchExpand = $('.search-expand');
function toggleSearch() {
// Reverse state
isSearchFieldOpen = !isSearchFieldOpen;
$toggleSearch.toggleClass('active');
// You can use callback function instead of using setTimeout
$searchExpand.fadeToggle(250, function() {
if (isSearchFieldOpen) {
$searchExpand.find('input').focus();
}
});
}
$toggleSearch.on('click', function(e) {
e.stopPropagation();
toggleSearch();
});
$(document.body).on('click', function(e) {
if (isSearchFieldOpen) {
var target = e.target;
// Checking if user clicks outside .search-expand
if (!$searchExpand.is(target) && !$searchExpand.has(target).length) {
toggleSearch();
}
}
});
I have a second search on the site with the same code as before only
with div .toggle-serach2 and .expand-search2, how can i make your code
so it wont overlap. just changing the name to $('toggle-search2')
doesn't cut it
in that case, I would suggest you convert your code into a plugin:
(function($, document) {
var bodyHandlerAttached = false;
var openedForms = [];
var instances = {};
var defaults = {
activeClass: 'active'
};
function ToggleSearch(elem, options) {
this.options = $.extend({}, defaults, options);
this.$elem = $(elem);
this.$btn = $(options.toggleBtn);
this.isOpen = false;
this.id = generateId();
this.bindEvents();
instances[this.id] = this;
if (!bodyHandlerAttached) {
handleOutsideClick();
bodyHandlerAttached = true;
}
}
ToggleSearch.prototype = {
bindEvents: function() {
this.$btn.on('click', $.proxy(toggleHandler, this));
},
open: function() {
if (this.isOpen) { return; }
var _this = this;
this.$btn.addClass(this.options.activeClass);
this.$elem.fadeIn(250, function() {
_this.$elem.find('input').focus();
});
openedForms.push(this.id);
this.isOpen = true;
},
close: function(instantly) {
if (!this.isOpen) { return; }
this.$btn.removeClass(this.options.activeClass);
if (instantly) {
this.$elem.hide();
} else {
this.$elem.fadeOut(250);
}
openedForms.splice(openedForms.indexOf(this.id), 1);
this.isOpen = false;
},
toggle: function() {
if (this.isOpen) {
this.close();
} else {
this.open();
}
}
};
var toggleHandler = function(ev) {
ev.stopPropagation();
this.toggle();
};
var handleOutsideClick = function(e) {
$(document.body).on('click', function(e) {
if (openedForms.length) {
var target = e.target;
var instance;
for (var id in instances) {
instance = instances[id];
if (!instance.$elem.is(target) && !instance.$elem.has(target).length) {
instance.close(true);
}
}
}
});
};
function generateId() {
return Math.random().toString(36).substr(2, 8);
}
$.fn.toggleSearch = function(options) {
return this.each(function() {
if (!$.data(this, 'toggleSearch')) {
$.data(this, 'toggleSearch', new ToggleSearch(this, options));
}
});
};
})(window.jQuery, document);
And then use it like this:
$('.search-expand').toggleSearch({
toggleBtn: '.toggle-search'
});
$('.search-expand2').toggleSearch({
toggleBtn: '.toggle-search2'
});
JSFiddle example
You could add a click handler to the main window that removes the active class:
$(window).click(function(){
$('.toggle-search').removeClass('active');
}
and then prevent the class removal when you click inside of your toggle-search elem
$('.toggle-search').click(function(e){
e.stopPropagation();
// remainder of click code here
)};
Try to add body click listener
$('body').click(function(e){
if ($(e.target).is('.toggle-search')) return;
$('.toggle-search').removeClass('active');
$('.search-expand').fadeOut(250);
});
I have recently started using JsFormValidatorBundle to validate my forms on symfony. The only issue is that i need to send these forms with Ajax and unfortunately for some reason the JsFormValidatorBundle forces the form to be sent by reloading the page.
So now i am trying to override that function which looks like:
function FpJsCustomizeMethods() {
...
this.submitForm = function (event) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var element = item.jsFormValidator;
if (event) {
event.preventDefault();
}
element.validateRecursively();
if (FpJsFormValidator.ajax.queue) {
if (event) {
event.preventDefault();
}
FpJsFormValidator.ajax.callbacks.push(function () {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
item.submit();
}
});
} else {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
item.submit();
}
}
});
};
....
}
if i remove the item.submit() it works perfectly.
So how can override this?
full script
You just need to make a new function and extend the parent via its prototype.
Perhaps this code block can explain what you need to do.
function Parent() {
this.a = function() {
alert("i am here");
}
this.submitForm = function() {
alert("i am wrong one here");
}
}
function Child () {
//we need to override function submitForm with right one
this.submitForm = function() {
alert("i am right one here");
}
}
Child.prototype = new Parent;
var c = new Child();
//other parent methods are still accessible.
c.a();
//method submitForm is overriden with the one we defined
c.submitForm();
see it in action here
As I suggested you actually don't want to overwrite the FpJsFormValidator.customizeMethods.submitForm function just to be able to submit your forms via Ajax instead of default. Doing so will result in:
code duplication as you would be forced to restore all of the validation parts in your own function
and if part of your solution would be getting rid of the item.submit() bits then you would also lose any other events bound to be driggered by that submit as a by product.
I would instead simply create a handler for the submit event on that item which would call event.preventDefault() and do the Ajax request. As you tagged your question with jQuery, something like:
$("#your_fav_form_selector").submit(function (e) {
e.preventDefault();
// fetch form data and send it off with $.ajax etc
});
There's 2 ways of doing that.
As far as I know, the function you want to override isn't a jQuery function. I kept the 2 examples so that you can decide which one fits in your code.
If it's a JavaScript function (custom or native)
First of all, I saw the function you're using and I find that it's hard to override a specific part of it, so I wrote it again and removed (or commented out) the "submit call" and then I've overridden the function. When calling FpJsFormValidator, the following function will be called NewFpJsCustomizeMethods.
<script type="text/javascript">
FpJsFormValidator = function() {
return NewFpJsCustomizeMethods();
}
function NewFpJsCustomizeMethods() {
this.init = function (options) {
FpJsFormValidator.each(this, function (item) {
if (!item.jsFormValidator) {
item.jsFormValidator = {};
}
for (var optName in options) {
switch (optName) {
case 'customEvents':
options[optName].apply(item);
break;
default:
item.jsFormValidator[optName] = options[optName];
break;
}
}
}, false);
return this;
};
this.validate = function (opts) {
var isValid = true;
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var method = (opts && true === opts['recursive'])
? 'validateRecursively'
: 'validate';
var validateUnique = (!opts || false !== opts['findUniqueConstraint']);
if (validateUnique && item.jsFormValidator.parent) {
var data = item.jsFormValidator.parent.data;
if (data['entity'] && data['entity']['constraints']) {
for (var i in data['entity']['constraints']) {
var constraint = data['entity']['constraints'][i];
if (constraint instanceof FpJsFormValidatorBundleFormConstraintUniqueEntity && constraint.fields.indexOf(item.name)) {
var owner = item.jsFormValidator.parent;
constraint.validate(null, owner);
}
}
}
}
if (!item.jsFormValidator[method]()) {
isValid = false;
}
});
return isValid;
};
this.showErrors = function (opts) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
item.jsFormValidator.errors[opts['sourceId']] = opts['errors'];
item.jsFormValidator.showErrors.apply(item, [opts['errors'], opts['sourceId']]);
});
};
this.submitForm = function (event) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var element = item.jsFormValidator;
if (event) {
event.preventDefault();
}
element.validateRecursively();
if (FpJsFormValidator.ajax.queue) {
if (event) {
event.preventDefault();
}
FpJsFormValidator.ajax.callbacks.push(function () {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
//item.submit();
}
});
} else {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
//item.submit();
}
}
});
};
this.get = function () {
var elements = [];
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
elements.push(item.jsFormValidator);
});
return elements;
};
//noinspection JSUnusedGlobalSymbols
this.addPrototype = function(name) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var prototype = FpJsFormValidator.preparePrototype(
FpJsFormValidator.cloneObject(item.jsFormValidator.prototype),
name,
item.jsFormValidator.id + '_' + name
);
item.jsFormValidator.children[name] = FpJsFormValidator.createElement(prototype);
item.jsFormValidator.children[name].parent = item.jsFormValidator;
});
};
//noinspection JSUnusedGlobalSymbols
this.delPrototype = function(name) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
delete (item.jsFormValidator.children[name]);
});
};
}
</script>
If it's a jQuery function
First of all, I saw the function you're using and I find that it's hard to override a specific part of it, so I wrote it again and removed (or commented out) the "submit call" and then I've overridden the jQuery function. When calling FpJsFormValidator, the following function will be called NewFpJsCustomizeMethods.
Here's the code:
<script type="text/javascript">
(function(){
// Define overriding method
jQuery.fn.FpJsFormValidator = NewFpJsCustomizeMethods();
})();
function NewFpJsCustomizeMethods() {
this.init = function (options) {
FpJsFormValidator.each(this, function (item) {
if (!item.jsFormValidator) {
item.jsFormValidator = {};
}
for (var optName in options) {
switch (optName) {
case 'customEvents':
options[optName].apply(item);
break;
default:
item.jsFormValidator[optName] = options[optName];
break;
}
}
}, false);
return this;
};
this.validate = function (opts) {
var isValid = true;
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var method = (opts && true === opts['recursive'])
? 'validateRecursively'
: 'validate';
var validateUnique = (!opts || false !== opts['findUniqueConstraint']);
if (validateUnique && item.jsFormValidator.parent) {
var data = item.jsFormValidator.parent.data;
if (data['entity'] && data['entity']['constraints']) {
for (var i in data['entity']['constraints']) {
var constraint = data['entity']['constraints'][i];
if (constraint instanceof FpJsFormValidatorBundleFormConstraintUniqueEntity && constraint.fields.indexOf(item.name)) {
var owner = item.jsFormValidator.parent;
constraint.validate(null, owner);
}
}
}
}
if (!item.jsFormValidator[method]()) {
isValid = false;
}
});
return isValid;
};
this.showErrors = function (opts) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
item.jsFormValidator.errors[opts['sourceId']] = opts['errors'];
item.jsFormValidator.showErrors.apply(item, [opts['errors'], opts['sourceId']]);
});
};
this.submitForm = function (event) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var element = item.jsFormValidator;
if (event) {
event.preventDefault();
}
element.validateRecursively();
if (FpJsFormValidator.ajax.queue) {
if (event) {
event.preventDefault();
}
FpJsFormValidator.ajax.callbacks.push(function () {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
//item.submit();
}
});
} else {
element.onValidate.apply(element.domNode, [FpJsFormValidator.getAllErrors(element, {}), event]);
if (element.isValid()) {
//item.submit();
}
}
});
};
this.get = function () {
var elements = [];
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
elements.push(item.jsFormValidator);
});
return elements;
};
//noinspection JSUnusedGlobalSymbols
this.addPrototype = function(name) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
var prototype = FpJsFormValidator.preparePrototype(
FpJsFormValidator.cloneObject(item.jsFormValidator.prototype),
name,
item.jsFormValidator.id + '_' + name
);
item.jsFormValidator.children[name] = FpJsFormValidator.createElement(prototype);
item.jsFormValidator.children[name].parent = item.jsFormValidator;
});
};
//noinspection JSUnusedGlobalSymbols
this.delPrototype = function(name) {
//noinspection JSCheckFunctionSignatures
FpJsFormValidator.each(this, function (item) {
delete (item.jsFormValidator.children[name]);
});
};
}
</script>
Second of all, if you're looking to override some stuff in the function:
<script type="text/javascript">
(function(){
// Store a reference to the original method.
var originalMethod = jQuery.fn.FpJsFormValidator;
// Define overriding method.
jQuery.fn.FpJsFormValidator = function(){
// Execute the original method.
originalMethod.apply( this, arguments );
}
})();
</script>
Note:
You need to write this code after loading the original function.
So I'm attempting to implement some google analytics event tracking on dynamically generated pages. I'll be using something like
<script>
$(document).ready(function(){
$("#button1").click(function(){
_gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction)']);
});
$("#button2").click(function(){
_gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction']);
});
});
</script>
I'm wondering is it possible to use something like document.title to auto generate the category section of the GA code from the html title of the pages? All the pages use unique titles and it would be great if the events tracked on those pages could show up in GA as separate entries and not just category.
That was tougher than I expected it. Hope it helps.
Live demo with examples
javascript
// Unbind default behaviour
$(document).off("ready.ga").on("ready", function () {
//hollow out
pageLoc = $(location).attr('href');
// Introduce helper functions.
(function ($, window, undef) {
// ga selector.
$.extend($.expr[":"], {
ga: function (a) {
var attr = a.attributes,
len = attr.length;
while (len--) {
if (attr[len].name.indexOf("data-ga-") !== -1) {
return true;
}
}
return false;
}
});
$.gaaApi = {
trackEvent: {
event: {
value: "_trackEvent",
validation: "isString",
type: "string"
},
category: {
value: null,
validation: "optString",
type: "currentloc"
},
action: {
value: null,
validation: "optString",
type: "string"
},
label: {
value: null,
validation: "optString",
type: "string"
},
value: {
value: null,
validation: "optInt",
type: "integer"
},
nonInteraction: {
value: null,
validation: "optBool",
type: "boolean"
}
},
trackPageview: {
event: {
value: ["trackPageview", $(location).attr('href')],
validation: "isString",
type: "string"
},
url: {
value: undef,
validation: "optString",
type: "string"
}
}
};
var validation = {
isString: function (obj) {
var empty = true;
if (obj && typeof obj === "string") {
empty = /^\s*$/.test(obj);
}
// If empty === true then something is wrong and we should return false.
return !(empty);
},
optString: function (obj) {
if (obj === undef) {
return true;
}
return validation.isString(obj);
},
isInt: function (obj) {
return (/^[\-+]?\d+$/).test(obj) || (obj === +obj && obj === (obj | 0));
},
optInt: function (obj) {
if (obj === undef) {
return true;
}
return validation.isInt(obj);
},
isFloat: function (obj) {
return (/^[\-+]?\d+(\.\d+)?$/).test(obj) || (obj === +obj && obj !== (obj | 0));
},
optFloat: function (obj) {
if (obj === undef) {
return true;
}
return validation.isFloat(obj);
},
isBool: function (obj) {
return (obj === true || obj === "true") || (obj === false || obj === "false");
},
optBool: function (obj) {
if (obj === undef) {
return true;
}
return validation.isBool(obj);
}
},
methods = {
validate: function (param, name, location) {
var $element = this.$element,
data = $element.data("ga-" + name.toLowerCase()),
isValid;
//pageLoc = $(location).attr('href');
if (!validation[param.validation]) {
throw new TypeError("Unknown validation type");
}
// Check the value.
isValid = validation[param.validation](data);
if (!isValid) {
throw new Error("object validation error on " + name);
}
// Assign the value.
// Some analytics methods accept numbers as strings so we check the return type.
switch (param.type) {
case "integer":
return data ? parseInt(data, 10) : null;
case "float":
return data ? parseFloat(data) : null;
case "boolean":
return data ? Boolean(data) : null;
case "currentloc":
return data;
default:
// Default to string.
return data ? data + "" : null;
}
},
createArgs: function () {
var binder = this,
event = this.event,
args = $.map(event, function (val, key, pageLoc) {
var pageLoc = $(location).attr('href');
var value;
if (key === "event") {
// We don't want to check for the event property in the DOM.
value = val.value;
} else {
// Validate and return the correct value from the DOM.
value = methods.validate.call(binder, val, key, pageLoc);
}
return value;
});
return args;
}
},
gaa = function (element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.gaa.defaults, options);
};
gaa.prototype = {
constructor: gaa,
trackEvent: function () {
var trackedEvent = $.Event("tracked.ga");
var currentLoc = $(location).attr('href');
this.args = methods.createArgs.call(this);
if (this.options.logit) {
if (window.console && window.console.log) {
// Push the data.
console.log("pushing to Google analytics", this.args);
this.$element.trigger(trackedEvent).trigger(currentLoc);
// this.$element.trigger(currentLocation);
}
} else {
var gaq = window._gaq;
if (gaq) {
// Set the context for our deferred callback.
var binder = this;
// Push the data.
$.when(gaq.push(args)).done(
function () {
this.$element.trigger(trackedEvent);
// this.$element.trigger(trackedEvent);
// Redirect the location - delayed so that any other page functionality has time to run.
setTimeout(function () {
var href = binder.attr("href");
if (href && href.indexOf("#") !== 0) {
window.location = href;
}
}, 100);
});
} else {
throw new ReferenceError(" _gaq not there");
}
}
}
};
// wrapper definition
$.fn.gaa = function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data("ga"),
opts = typeof options === "object" ? options : null;
if (!data) {
// Check the data and assign if not present.
$this.data("ga", (data = new gaa(this, opts)));
}
// Run the appropriate function is a string is passed.
if (typeof options === "string") {
data[options]();
} else {
var handler = data.options.handler.toLowerCase(),
// Check for the event attr here as it might be other than the default.
event = data.$element.attr("data-ga-event");
// Overwrite if necessary.
$.extend(data.options, {
event: event
});
// Build the data as we have nothing there.
// First assign the event.
data.event = $.gaaApi[data.options.event];
// Then bind the handler.
if (handler === "load") {
data.trackEvent();
} else {
data.$element.on(handler + ".ga", function (e) {
e.preventDefault();
data.trackEvent();
});
}
}
});
};
// Define the defaults.
$.fn.gaa.defaults = {
event: ["trackEvent", "giveLocation"],
handler: "load",
logit: false
};
// Set the public constructor.
$.fn.gaa.Constructor = gaa;
// Let's BEGIN
$(document).on("ready.ga", function () {
// Bind using the custom selector.
$(":ga").each(function () {
$(this).gaa();
});
});
}(jQuery, window));
// Set some options the ones below are the defaults.
var options = {
event: "trackEvent", // The event name unprefixed.
handler: "click", // The eventhandler to trigger the tracking.
// Using 'load' will track immediately.
logit: true, //to logit
};
var options2 = {
event: "trackPageview", // The event name unprefixed.
handler: "click", // The eventhandler to trigger the tracking.
// Using 'load' will track immediately.
logit: true, //to logit
};
var options3 = {
event: "trackPageview", // The event name unprefixed.
handler: "load", // The eventhandler to trigger the tracking.
// Using 'load' will track immediately.
logit: true //to logit
};
// Binds using the custom selector.
$("load.trigger").gaa(options3); //fires a ga onload after domready
$("button.button1").gaa(options2).click(function () {
console.log('\nmore button events\n', 'heres the URL:', location.href)
});
$("#clickme").gaa(options).click(function () {
$(this).toggleClass("changeIt");
});
});
index.html
<load class="trigger">loading triggers ga event</load>
<button class="button1">fire ga event with address</button>
<button class="button1" id="clickme">multiple events</button>
The location bind happens here and lets jquery consume location properly.
event: {
value: ["trackPageview",$(location).attr('href')],
validation: "isString",
type: "string"
}
your approach of using this was correct but you had to get the location earlier to get it into ga. It seems like anyways this format
$("#button").gaa(options).click(function () {
$(this).toggleClass("changeIt");
});
Will get you going in the right directions.
This was a fun brainache. That should give you access to location.href where you want need it later on. The idea is to form a bind after DOM ready but before _gaq execution.
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');