jquery toggle function and set a cookie - function

I have the following function which toggles mouseenter and mouseleave on click:
var flag = true;
$('.aaa').mouseenter(function () {
if(flag) {
$(this).css('background', '#aaaaaa');
}
$(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
if(flag) {
$(this).css('background','blue');
}
$(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
flag = !flag;
});
http://jsfiddle.net/z8KuE/15/
How can chosen preference be "remembered" and loaded on the next page load?
edit: in case that the solution from bellow doesn't work on the site for some reason, just put it here:
(function($){
$(document).ready(function(){
//Scripts go in here!
});
})(jQuery);

I would use the jQuery cookie plugin:
var storedFlag = $.cookie('userSelection'); // read cookie
var flag = 1; //default value
if(storedFlag != undefined){ // some flag was stored
flag = storedFlag;
}
$('.aaa').mouseenter(function () {
if(flag > 0) {
$(this).css('background', '#aaaaaa');
}
$(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
if(flag > 0) {
$(this).css('background','blue');
}
$(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
flag = 1 - flag;
$.cookie('userSelection', flag, { expires: 30 }); // store cookie
});
The problem is that the boolean values are stored as strings, and the string 'false' is a true value, thus i resorted to using numbers and >0 comparison.
See updated fiddle

Related

canvas is throw error of tainted after LoadFromJson

I am using fabric js version 1.7.22
when image set in a repetitive manner in a rectangle of fabric js, at
the first time it will be loaded and saved into JSON using toJSON()
and save an image using todataUrl() method, but when cal canvas a loadFromJson method at that time, this canvas not savable, because it throws tainted canvas error.
Please help me,
I already set crossOrigin in a pattern but it not working. and not
added in canvas JSON.
I have made one Fiddle For Generate Issue :
[http://jsfiddle.net/Mark_1998/kt387vLc/1/][1]
Steps to generate issue :
click on 'set pattern'
then click on 'save canvas'
then click on 'reload canvas' // load canvas from JSON
then click on 'save canvas' // cause issue of tainted canvas
This issue is fixed in new version of fabricjs already. If you are still using 1.7.20 the override fabric.Pattern.prototype.toObject and fabric.Pattern.prototype.initialize, find code in snippet.
var canvas = new fabric.Canvas('canvas', {
height: 500,
width: 500,
});
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
var canvasJSON = {};
document.getElementById('setPat').addEventListener('click', function() {
fabric.util.loadImage('https://cdn.dribbble.com/assets/icon-backtotop-1b04df73090f6b0f3192a3b71874ca3b3cc19dff16adc6cf365cd0c75897f6c0.png', function(image) {
var pattern = new fabric.Pattern({
source: image,
repeat: 'repeat',
crossOrigin: 'Anonymous'
});
var patternObject = new fabric.Rect({
left: 0,
top: 0,
height: canvas.height,
width: canvas.width,
angle: 0,
fill: pattern,
objectCaching: false
})
canvas.add(patternObject);
}, null, {
crossOrigin: 'Anonymous'
});
})
document.getElementById('saveCanvas').addEventListener('click', function() {
console.log('save canvas');
canvasJSON = canvas.toJSON();
var image = canvas.toDataURL("image/png", {
crossOrigin: 'Anonymous'
}); // don't remove this, i need it as thumbnail.
//console.log('canvas.Json', canvasJSON);
//console.log('image', image);
canvas.clear();
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
});
document.getElementById('reloadCanvas').addEventListener('click', function() {
console.log('save canvas');
canvas.loadFromJSON(canvasJSON, function() {
canvas.set({
crossOrigin: 'Anonymous'
})
});
console.log('canvas.Json', canvasJSON);
});
//cross origin was not added in toObject JSON
fabric.Pattern.prototype.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
crossOrigin: this.crossOrigin,
patternTransform: this.patternTransform ? this.patternTransform.concat() : null
});
};
})(fabric.Pattern.prototype.toObject);
//cross origin was not added while creating image
fabric.Pattern.prototype.initialize = function(options, callback) {
options || (options = {});
this.id = fabric.Object.__uid++;
this.setOptions(options);
if (!options.source || (options.source && typeof options.source !== 'string')) {
callback && callback(this);
return;
}
// function string
if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
this.source = new Function(fabric.util.getFunctionBody(options.source));
callback && callback(this);
} else {
// img src string
var _this = this;
this.source = fabric.util.createImage();
fabric.util.loadImage(options.source, function(img) {
_this.source = img;
callback && callback(_this);
}, null, this.crossOrigin);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<button id="setPat">
Set pattern
</button>
<button id="saveCanvas">
Save canvas
</button>
<button id="reloadCanvas">
Reload CAnvas
</button>
<canvas id="canvas"></canvas>

Jquery UI autcomplete with Json data source

I am using jquery UI autocomple with json data source but it's not working but when I used same with fixed data it works. Below is my code.
$(document).ready(function () {
var codes = "";
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
if (response.status != false) {
if (response.CPTCodeCount > 0) {
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes = codes + "'" + item.ShortName + "'";
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: [codes],//['Tom', 'Alex', 'Patrick'],
});
});
Based on jQueryUI's API, the source option can either be an array or a String that points to an URL or a Function. Furthermore, your code needs to change few things so that the array is handled in appropriate fashion:
$(document).ready(function () {
var codes = []; // array is created
Admin_BasicFeeSchedule.LoadCPTCodes().done(function (response) {
//alert("LoadCPTCodes works") ;
if (response.status != false) {
//alert("response.status true") ;
if (response.CPTCodeCount > 0) {
//alert("CPTCodeCount > 0") ;
var CPTCodeLoadJSONData = JSON.parse(response.CPTCodeLoad_JSON);
$.each(CPTCodeLoadJSONData, function (i, item) {
codes.push(item.ShortName); //add item to an array
});
//codes = codes + "]";
alert(codes);
}
}
else {
utility.DisplayMessages(response.Message, 3);
}
});
$.widget("ui.autocomplete", $.ui.autocomplete, {
_renderMenu: function (ul, items) {
var that = this;
$.each(items, function (index, item) {
that._renderItemData(ul, item);
});
$(ul).wrap("<div></div>");
},
});
$("input#ddlCPTCode").autocomplete({
source: codes // pass an array (without a comma)
});
});
Finally, if those changes related to the array aren't enough to make it work, then I would check the JSON load part. I have added some alert calls that can be uncommented for JSON testing purposes. As I am not familiar with the details of the JSON load functionality that is used in the sample code, then I'm just going to mention that there are alternative ways of loading JSON data such as jQuery's getJSON method.

jquery sidebar putting next to each other

I have put together a sidebar with hover-delay animation, but I can't seem to exactly copy the column to place next to the first. This is my first problem.
The second is that I would like to use the jspanel plugin, so that a dragable window will pop up when I click on a sub-item in the sidebar.
I hope this can be brought to a working state.
Thank you very much for responses in advance!
Here's [a link] (http://jsfiddle.net/chrisoutwright/tc4d9t6d/)!
$('#categories').corner("top keep");
$(document).ready(function(){
$("#foo").click(function(){
$().jsPanel().show();
});
});
$( "#navigation ul.sub-level" ).corner("").css( "border", "3px double blue" );
jQuery.fn.hoverWithDelay = function(inCallback,outCallback,delay) {
this.each(function() {
var timer, $this = this;
$(this).hover(function(){
timer = setTimeout(function(){
timer = null;
inCallback.call($this);
}, delay);
},function() {
if (timer) {
clearTimeout(timer);
timer = null;
} else
outCallback.call($this);
});
});
};
var hovering = {mainMenu: false, categories: false};
function closeSubMenus() {
$('ul.sub-level').css('display', 'none');
}
closeSubMenus();
function closeMenuIfOut() {
setTimeout(function(){
if (!hovering.mainMenu && !hovering.categories) {
$('#navigation').fadeOut('fast',closeSubMenus);
}
},100);
}
$('ul.top-level li').hoverWithDelay(function() {
$(this).find('ul').show();
}, function() {
$(this).find('ul').fadeOut('fast', closeMenuIfOut);
}, 500);
$('#categories').hoverWithDelay(function() {
$('#navigation').show();
hovering.categories = true;
},
function(){
hovering.categories = false;
closeMenuIfOut();
},500);
$('#navigation').hover(function() {
hovering.mainMenu = true;
}, function() {
hovering.mainMenu = false;
});
I can see at least one error in line 4 where you try to generate/open the jsPanel.
Which jsPanel version do you use? Version 1.x or Version 2.x? The two versions differ on how to use the jsPanel() command.
version 1.x: $( selector ).jsPanel( config );
version 2.x: $.jsPanel( config );
Do you get any error messages?

Firefox html5 drag and drop not working

I know there are a lot of similar questions on here, but, when putting them to action, I still resolve in the same problem.
I have 2 angular directives (drag and drop) and one angular factory (dndAPI). This is all based off of fisshy's Angular Drag and Drop on github.
I finally got firefox to accept and drag movement by adding data to the event, however I can't seem to keep it from doing it's default behavior (and loading that data as a url). I also apologize I couldn't get it to work at all on jsfiddle...at all. I'll try again if someone can't see if I'm doing something outrageously wrong.
angular.module('dragAndDrop', [])
.directive('drag',function (dndApi) {
var drags = [],
dragging = new RegExp('(\\s|^)dragging(\\s|$)');
return {
restrict: 'A',
scope: {
item: '=drag',
whenStart: '&',
whenEnd: '&',
dropzones: '='
},
link: function (scope, elem, attr, ctrl) {
elem.bind('dragstart', function (e) {
angular.element('query-tool-tip').removeClass('active');
//if ( drags.length === 0 ) {
drags = document.querySelectorAll('.drop');
//}
angular.forEach(drags, function (value, key) {
if (scope.dropzones.indexOf(value.getAttribute('drop')) >= 0) {
value.className = value.className + ' dragging';
}
});
elem.addClass('dragging');
dndApi.setData(scope.item, scope.dropzones);
e.originalEvent.dataTransfer.effectAllowed = 'move';
//KEEPS FIREFOX FROM CRAPPING OUT:
e.originalEvent.dataTransfer.setData( 'text/plain', 'stop' );
scope.$apply(function () {
scope.whenStart({ data: dndApi.getData() });
});
});
elem.bind('dragleave', function(e){});
elem.bind('dragend', function (e) {
elem.removeClass('dragging');
angular.forEach(drags, function (value, key) {
value.className = value.className.replace(dragging, '');
});
scope.$apply(function () {
scope.whenEnd({ data: dndApi.getData() });
});
dndApi.removeData();
e.preventDefault();
});
elem[0].draggable = true;
elem[0].className = elem[0].className + ' drag';
}
};
}).directive('drop',function (dndApi) {
var drags = [],
dragging = new RegExp('(\\s|^)dragging(\\s|$)');
return {
scope: {
drop: '=drop',
whenDrop: '&',
whenEnter: '&',
whenLeave: '&',
queryIndex: "=queryIndex",
hideElem: '='
},
link: function (scope, elem, attr, ctrl) {
var left = elem[0].offsetLeft,
right = left + elem[0].offsetWidth,
top = elem[0].offsetTop,
bottom = top + elem[0].offsetHeight;
elem.bind('drop', function (e) {
// e.originalEvent.preventDefault();
//if (e.stopPropagation()) {
// e.stopPropagation();
//e.originalEvent.stopPropagation();
//e.preventDefault();
//e.originalEvent.preventDefault();
//}
e.originalEvent.dataTransfer.clearData();
if (dndApi.getDropZones().indexOf(scope.drop) >= 0) {
scope.$apply(function () {
scope.whenDrop({ data: dndApi.getData(), queryI: scope.queryIndex });
});
}
if (drags.length === 0) {
drags = document.querySelectorAll('.drop');
}
angular.forEach(drags, function (value, key) {
value.className = value.className.replace(dragging, '');
});
dndApi.removeData();
e.stopPropagation();
e.originalEvent.stopPropagation();
e.preventDefault();
e.originalEvent.preventDefault();
});
elem.bind('dragenter', function (e) {
e.preventDefault();
e.originalEvent.preventDefault();
if (elem[0] == e.target) {
scope.$apply(function () {
scope.whenEnter({ data: dndApi.getData() });
});
}
return false;
});
elem.bind('dragleave', function (e) {
e.preventDefault();
e.originalEvent.preventDefault();
if ((e.x < left || e.x > right) ||
(e.y < top || e.y > bottom)) {
scope.$apply(function () {
scope.whenLeave({ data: dndApi.getData() });
});
}
return false;
});
elem.bind('dragover', function (e) {
//if (e.preventDefault) {
e.preventDefault();
e.originalEvent.preventDefault();
//}
return false;
});
elem[0].className = elem[0].className + ' drop';
scope.$watch('hideElem', function () {
if (scope.hideElem === true) {
elem.hide();
} else {
elem.show();
}
});
}
};
}).factory('dndApi', function () {
var dnd = {
dragObject: {},
dropzones: []
};
return {
setData: function (data, areas) {
dnd.dragObject = data;
dnd.dropzones = areas;
},
removeData: function () {
dnd.dragObject = null;
dnd.dropZones = [];
},
getData: function () {
return dnd.dragObject;
},
getDropZones: function () {
return dnd.dropzones;
}
};
});
I've done a lot of what's recommended on other questions. I've added event.preventDefault() to the dragenter and dragleave spots. And then when that didn't work I added them everywhere. I have a feeling it has to do with my drop method. If i put event.prevendDefault() at the beginning of the binding, the rest of my code isn't executed.
Any advice, even if it's something small that I might've overlooked, will be helpful.
Thanks!
You are calling e.originalEvent.dataTransfer.clearData(); in the drop event handler which will cause an exception to be thrown (you won't have permission to alter the original dataTransfer object). This is preventing e.originalEvent.preventDefault(); from being called.

html color to alternative rows of dynamic table

I have a Dynamic table that I want to give color to on alternative rows. How can I achieve this with css? I need the code to work in IE7+
Look into using even/odd rules in CSS3.
Reference: https://developer.mozilla.org/en/CSS/:nth-child
For instance,
tr:nth-child(odd) will represent the CSS for every 2n + 1 child, whereas tr:nth-child(even) will represent the CSS for every 2n child.
i came across this same problem Friday, i used the jquery solution of
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
a stack overflow solution .js posted here
Detect changes in the DOM
so essentially you add the .js script in the head and fire the jquery rules on dom change.
My finished .js looked like this
<script type="text/javascript">
(function (window) {
var last = +new Date();
var delay = 100; // default delay
// Manage event queue
var stack = [];
function callback() {
var now = +new Date();
if (now - last > delay) {
for (var i = 0; i < stack.length; i++) {
stack[i]();
}
last = now;
}
}
// Public interface
var onDomChange = function (fn, newdelay) {
if (newdelay)
delay = newdelay;
stack.push(fn);
};
// Naive approach for compatibility
function naive() {
var last = document.getElementsByTagName('*');
var lastlen = last.length;
var timer = setTimeout(function check() {
// get current state of the document
var current = document.getElementsByTagName('*');
var len = current.length;
// if the length is different
// it's fairly obvious
if (len != lastlen) {
// just make sure the loop finishes early
last = [];
}
// go check every element in order
for (var i = 0; i < len; i++) {
if (current[i] !== last[i]) {
callback();
last = current;
lastlen = len;
break;
}
}
// over, and over, and over again
setTimeout(check, delay);
}, delay);
}
//
// Check for mutation events support
//
var support = {};
var el = document.documentElement;
var remain = 3;
// callback for the tests
function decide() {
if (support.DOMNodeInserted) {
window.addEventListener("DOMContentLoaded", function () {
if (support.DOMSubtreeModified) { // for FF 3+, Chrome
el.addEventListener('DOMSubtreeModified', callback, false);
} else { // for FF 2, Safari, Opera 9.6+
el.addEventListener('DOMNodeInserted', callback, false);
el.addEventListener('DOMNodeRemoved', callback, false);
}
}, false);
} else if (document.onpropertychange) { // for IE 5.5+
document.onpropertychange = callback;
} else { // fallback
naive();
}
}
// checks a particular event
function test(event) {
el.addEventListener(event, function fn() {
support[event] = true;
el.removeEventListener(event, fn, false);
if (--remain === 0) decide();
}, false);
}
// attach test events
if (window.addEventListener) {
test('DOMSubtreeModified');
test('DOMNodeInserted');
test('DOMNodeRemoved');
} else {
decide();
}
// do the dummy test
var dummy = document.createElement("div");
el.appendChild(dummy);
el.removeChild(dummy);
// expose
window.onDomChange = onDomChange;
})(window);
$(document).ready(function () {
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
onDomChange(function () {
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
});
});
</script>
I would like to caveat this answer that this probably is not the greatest solution but worked for what i needed it to do. :-)
CSS3 nth-child selector:
tr:nth-child(odd) {
background: red /* or whatever */;
}
You can use a CSS3 selector:
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}
or jQuery:
$("tr:even").css("background-color", "#CCC");
$("tr:odd").css("background-color", "#FFF");
or do it on the server side.