How do I initiate the function on button click? - javascript

Following code starts a chess game in initial position integrating chess.js library.
var board = null
var game = new Chess()
var $status = $('#status')
var $fen = $('#fen')
var $pgn = $('#pgn')
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
})
// illegal move
if (move === null) return 'snapback'
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = ''
var moveColor = 'White'
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move'
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status)
$fen.html(game.fen())
$pgn.html(game.pgn())
}
var config = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
}
board = Chessboard('board2', config)
updateStatus()
After checkmate though there is no option to clear the board. Is there a way to integrate the following code so I can only start the game or the clear the board if the respective button is clicked? The start button places the pieces in their default position on a clear board using only the draggable function set to true within Chessboard.
$('#startBtn').on('click', board2.start)
$('#clearBtn').on('click', board2.clear)

I simply added the code for the buttons at the bottom of your code. This code attaches event handlers to the start and clear buttons, so it could be placed anywhere outside of a function. Here's some code to display the two buttons below the board. I also added some code to run the code inside the code snippet.
var board = null
var game = new Chess()
var $status = $('#status')
var $fen = $('#fen')
var $pgn = $('#pgn')
function onDragStart (source, piece, position, orientation) {
// do not pick up pieces if the game is over
if (game.game_over()) return false
// only pick up pieces for the side to move
if ((game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false
}
}
function onDrop (source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
})
// illegal move
if (move === null) return 'snapback'
updateStatus()
}
// update the board position after the piece snap
// for castling, en passant, pawn promotion
function onSnapEnd () {
board.position(game.fen())
}
function updateStatus () {
var status = ''
var moveColor = 'White'
if (game.turn() === 'b') {
moveColor = 'Black'
}
// checkmate?
if (game.in_checkmate()) {
status = 'Game over, ' + moveColor + ' is in checkmate.'
}
// draw?
else if (game.in_draw()) {
status = 'Game over, drawn position'
}
// game still on
else {
status = moveColor + ' to move'
// check?
if (game.in_check()) {
status += ', ' + moveColor + ' is in check'
}
}
$status.html(status)
$fen.html(game.fen())
$pgn.html(game.pgn())
}
pieceTemplates = ({wiki:'https://chessboardjs.com/img/chesspieces/wikipedia/{piece}.png',
alpha:'https://chessboardjs.com/img/chesspieces/alpha/{piece}.png'})
var config = {
draggable: true,
pieceTheme:pieceTemplates.wiki,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
}
board = Chessboard('board', config)
updateStatus()
$('#startBtn').on('click', function () {
game.reset()
board.start()
})
$('#clearBtn').on('click', function () {
game.reset()
board.clear()
})
<link rel="stylesheet"
href="https://unpkg.com/#chrisoakman/chessboardjs#1.0.0/dist/chessboard-1.0.0.min.css"
integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU"
crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/#chrisoakman/chessboardjs#1.0.0/dist/chessboard-1.0.0.min.js"
integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/chess.js#0.12.1/chess.js"></script>
<div id="board" style="width:400px;"></div>
<button id="startBtn">Start Position</button>
<button id="clearBtn">Clear Board</button>

Related

FabricJS selection handling multiple objects

I am struggling with handling the selection of multiple objects. The desired behaviour would be that each object that is clicked will be added to the current selection. Similar to holding shift-key, but also selections using the drag-options should be added to the existing selection. The current behaviour of fabricjs is creating a new selection even when pressing shift-key. In addition the selection should not be cleared when clicking a blank space on the canvas. Deselecting objects should only be possible when clicking a single object which is part of the selection (when dragging selected objects should stay selected). Or by clicking an additional button to clear the full selection (with additional user confirmation).
I tried different setups using "selection:created" and "selection:updated" but this either messed up the selection or resulted in an endless loop because modifying the selection inside the update also triggers the update again.
canvas.on("selection:updated", (event) => {
event.selected.forEach((fabImg) => {
if (!this.selectedImages.includes(fabImg)) {
this.selectedImages.push(fabImg);
}
});
var groupSelection = new fabric.ActiveSelection(this.selectedImages);
canvas.setActiveObject(groupSelection);
});
Preventing the clear when clicking on the blank canvas was solved by:
var selection = [];
canvas.on("before:selection:cleared", (selected) => {
selection = this.canvas.getActiveObjects();
});
canvas.on("selection:cleared", (event) => {
var groupSelection = new fabric.ActiveSelection(selection);
canvas.setActiveObject(groupSelection);
});
Just in case someone else is interested, I ended up changing 3 functions in the fabricjs code to achieve the desired behaviour:
canvas.class.js:
_shouldClearSelection: function (e, target) {
var activeObjects = this.getActiveObjects(),
activeObject = this._activeObject;
return (
(target &&
activeObject &&
activeObjects.length > 1 &&
activeObjects.indexOf(target) === -1 &&
activeObject !== target &&
!this._isSelectionKeyPressed(e)) ||
(target && !target.evented) ||
(target &&
!target.selectable &&
activeObject &&
activeObject !== target)
);
}
just removed the check if an object was clicked, to stop deselecting when clicking on blank space.
_isSelectionKeyPressed: function (e) {
var selectionKeyPressed = false;
if (this.selectionKey == "always") {
return true;
}
if (
Object.prototype.toString.call(this.selectionKey) === "[object Array]"
) {
selectionKeyPressed = !!this.selectionKey.find(function (key) {
return e[key] === true;
});
} else {
selectionKeyPressed = e[this.selectionKey];
}
return selectionKeyPressed;
}
just adding a "dummy" key called "always" to pretend always holding the shift-key. In canvas definition just add this key:
this.canvas = new fabric.Canvas("c", {
hoverCursor: "hand",
selection: true,
backgroundColor: "#F0F8FF",
selectionBorderColor: "blue",
defaultCursor: "hand",
selectionKey: "always",
});
And in canvas_grouping.mixin.js:
_groupSelectedObjects: function (e) {
var group = this._collectObjects(e),
aGroup;
var previousSelection = this._activeObject;
if (previousSelection) {
if (previousSelection.type === "activeSelection") {
var currentActiveObjects = previousSelection._objects.slice(0);
group.forEach((obj) => {
if (!previousSelection.contains(obj)) {
previousSelection.addWithUpdate(obj);
}
});
this._fireSelectionEvents(currentActiveObjects, e);
} else {
aGroup = new fabric.ActiveSelection(group.reverse(), {
canvas: this,
});
this.setActiveObject(aGroup, e);
var objects = this._activeObject._objects.slice(0);
this._activeObject.addWithUpdate(previousSelection);
this._fireSelectionEvents(objects, e);
}
} else {
// do not create group for 1 element only
if (group.length === 1 && !previousSelection) {
this.setActiveObject(group[0], e);
} else if (group.length > 1) {
aGroup = new fabric.ActiveSelection(group.reverse(), {
canvas: this,
});
this.setActiveObject(aGroup, e);
}
}
}
This will extend existing groups on drag-select instead of overwriting the existing selection.

Alterting cute file browser to be comaptible with any jquery version

I have been experimenting with cute file browser (perfect for my project).
Cute File Browser
But came accross a incomaptibiliy issue. Im not getting any errors in console, but im also not getting any elements being rendered. I have switched libraries about and I think this plugin only works with jquery version 1.11.0, the version my project is using is 1.11.3.
How should I attempt to fix/update this small script?
CUTE SCRIPT:
$(function(){
var filemanager = $('.filemanager'),
breadcrumbs = $('.breadcrumbs'),
fileList = filemanager.find('.data');
// Start by fetching the file data from scan.php with an AJAX request
$.get('scan.php', function(data) {
var response = [data],
currentPath = '',
breadcrumbsUrls = [];
var folders = [],
files = [];
// This event listener monitors changes on the URL. We use it to
// capture back/forward navigation in the browser.
$(window).on('hashchange', function(){
goto(window.location.hash);
// We are triggering the event. This will execute
// this function on page load, so that we show the correct folder:
}).trigger('hashchange');
// Hiding and showing the search box
filemanager.find('.search').click(function(){
var search = $(this);
search.find('span').hide();
search.find('input[type=search]').show().focus();
});
// Listening for keyboard input on the search field.
// We are using the "input" event which detects cut and paste
// in addition to keyboard input.
filemanager.find('input').on('input', function(e){
folders = [];
files = [];
var value = this.value.trim();
if(value.length) {
filemanager.addClass('searching');
// Update the hash on every key stroke
window.location.hash = 'search=' + value.trim();
}
else {
filemanager.removeClass('searching');
window.location.hash = encodeURIComponent(currentPath);
}
}).on('keyup', function(e){
// Clicking 'ESC' button triggers focusout and cancels the search
var search = $(this);
if(e.keyCode == 27) {
search.trigger('focusout');
}
}).focusout(function(e){
// Cancel the search
var search = $(this);
if(!search.val().trim().length) {
window.location.hash = encodeURIComponent(currentPath);
search.hide();
search.parent().find('span').show();
}
});
// Clicking on folders
fileList.on('click', 'li.folders', function(e){
e.preventDefault();
var nextDir = $(this).find('a.folders').attr('href');
if(filemanager.hasClass('searching')) {
// Building the breadcrumbs
breadcrumbsUrls = generateBreadcrumbs(nextDir);
filemanager.removeClass('searching');
filemanager.find('input[type=search]').val('').hide();
filemanager.find('span').show();
}
else {
breadcrumbsUrls.push(nextDir);
}
window.location.hash = encodeURIComponent(nextDir);
currentPath = nextDir;
});
// Clicking on breadcrumbs
breadcrumbs.on('click', 'a', function(e){
e.preventDefault();
var index = breadcrumbs.find('a').index($(this)),
nextDir = breadcrumbsUrls[index];
breadcrumbsUrls.length = Number(index);
window.location.hash = encodeURIComponent(nextDir);
});
// Navigates to the given hash (path)
function goto(hash) {
hash = decodeURIComponent(hash).slice(1).split('=');
if (hash.length) {
var rendered = '';
// if hash has search in it
if (hash[0] === 'search') {
filemanager.addClass('searching');
rendered = searchData(response, hash[1].toLowerCase());
if (rendered.length) {
currentPath = hash[0];
render(rendered);
}
else {
render(rendered);
}
}
// if hash is some path
else if (hash[0].trim().length) {
rendered = searchByPath(hash[0]);
if (rendered.length) {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
else {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
}
// if there is no hash
else {
currentPath = data.path;
breadcrumbsUrls.push(data.path);
render(searchByPath(data.path));
}
}
}
// Splits a file path and turns it into clickable breadcrumbs
function generateBreadcrumbs(nextDir){
var path = nextDir.split('/').slice(0);
for(var i=1;i<path.length;i++){
path[i] = path[i-1]+ '/' +path[i];
}
return path;
}
// Locates a file by path
function searchByPath(dir) {
var path = dir.split('/'),
demo = response,
flag = 0;
for(var i=0;i<path.length;i++){
for(var j=0;j<demo.length;j++){
if(demo[j].name === path[i]){
flag = 1;
demo = demo[j].items;
break;
}
}
}
demo = flag ? demo : [];
return demo;
}
// Recursively search through the file tree
function searchData(data, searchTerms) {
data.forEach(function(d){
if(d.type === 'folder') {
searchData(d.items,searchTerms);
if(d.name.toLowerCase().match(searchTerms)) {
folders.push(d);
}
}
else if(d.type === 'file') {
if(d.name.toLowerCase().match(searchTerms)) {
files.push(d);
}
}
});
return {folders: folders, files: files};
}
// Render the HTML for the file manager
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if(Array.isArray(data)) {
data.forEach(function (d) {
if (d.type === 'folder') {
scannedFolders.push(d);
}
else if (d.type === 'file') {
scannedFiles.push(d);
}
});
}
else if(typeof data === 'object') {
scannedFolders = data.folders;
scannedFiles = data.files;
}
// Empty the old result and make the new one
fileList.empty().hide();
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
}
else {
filemanager.find('.nothingfound').hide();
}
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name),
icon = '<span class="icon folder"></span>';
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
}
else {
itemsLength = 'Empty';
}
var folder = $('<li class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></li>');
folder.appendTo(fileList);
});
}
if(scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length-1];
icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>';
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li>');
file.appendTo(fileList);
});
}
// Generate the breadcrumbs
var url = '';
if(filemanager.hasClass('searching')){
url = '<span>Search results: </span>';
fileList.removeClass('animated');
}
else {
fileList.addClass('animated');
breadcrumbsUrls.forEach(function (u, i) {
var name = u.split('/');
if (i !== breadcrumbsUrls.length - 1) {
url += '<span class="folderName">' + name[name.length-1] + '</span> <span class="arrow">→</span> ';
}
else {
url += '<span class="folderName">' + name[name.length-1] + '</span>';
}
});
}
breadcrumbs.text('').append(url);
// Show the generated elements
fileList.animate({'display':'inline-block'});
}
// This function escapes special html characters in names
function escapeHTML(text) {
return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
}
// Convert file sizes from bytes to human readable units
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
});
I tweaked certain jquery methods around in the render function using the 1.11.3 version and it appears animate() was causing the issues.
Change Script.js line 375:
From fileList.animate({'display':'inline-block'});
To fileList.css('display','inline-block');.
EDIT:
I noticed a slightly more improved method of revealing the hidden filelist without using inline styles and adding it to a more appoporate section of the script. Simply use filelist.show() in the following section of the render function.
change Script.js line 286-291:
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
fileList.hide();
}
else {
filemanager.find('.nothingfound').hide();
fileList.show();
}
Hiding the filelist using filelist.hide() also helped me with a style bug relating to the .nothing-found error message being pushed down to the bottom of the page when needing to use a fixed height on the filelist.
Now im not depenedant on what version of jquery im using. Hope this helps others using this nice little script.

Add buttons inside javascript code

I want to add a button in javascript code I have which stores the heart rate from Gear 2 using Tizen sdk. In my code, the main div is inserted inside javascript code. I am using the following code:
//HTML CODE:
<div id="chartContainer" class="chart"></div>
//JAVASCRIPT CODE:
var chart = new CanvasJS.Chart("chartContainer",{
title :{
fontColor: "#ccc",
text: "Heart Rate"
},
backgroundColor: "#222",
data: [{
color: "#CD5C5C",
type: "line",
dataPoints: dps
}]
});
var lastSecond = -1;
var updateChart = function (heartrate) {
time = new Date().getTime() - initial;
console.log("[" + time + ", " + heartrate + "]");
temp = heartrate;
console.log("tempVar"+ temp);
tizen.filesystem.resolve(
'documents',
function(dir){
documentsDir = dir; dir.listFiles(onsuccess,onerror);
}, function(e) {
console.log("Error" + e.message);
}, "a"
);
dps.push({
x: time / 1000.0,
y: heartrate
});
if (dps.length > dataLength)
{
dps.shift();
}
var second = Math.round(time / 1000.0);
console.log(history.length);
if(lastSecond != second) {
// TODO use avg heart rate instead of smapshot.
history.push({
x: second,
y: heartrate
});
if(history.length > historyDataLength) {
history.shift();
}
lastSecond = second;
}
if(dps.length >= dataLength) {
chart.render();
}
var hrchart = "<center>" + heartrate + "bps</center><table width='100%' cellpadding=4px>";
for(var i = history.length - historyDataLength; i >= 0 && i < history.length; i++) {
hrchart += "<tr><td align='right' width='50%'>" + history[i].x + "s</td><td width='50%'>" + history[i].y + "bps</td></tr>";
}
hrchart += "</table>";
$('#textbox').html(hrchart);
};
updateChart(0);
updateChart(250);
for(var i = 0; i < dataLength; i++) {
updateChart(0);
}
I want to create a two buttons one for closing the application on click and one for storing data on click . How can I add those two buttons inside javascript code? Secondly is anyone familiar with "tizenhwkey" key? Which key is exactly? Thirdly I open the heartrate sensor using the following command window.webapis.motion.start("HRM", onchangedCB). How can I close the heart rate sensor? Function onchangeCB is the following:
function onchangedCB(hrmInfo)
{
if(hrmInfo.heartRate > 0) {
// add eventListener for tizenhwkey
document.addEventListener('tizenhwkey', function(e) {
if(e.keyName == "back")
tizen.application.getCurrentApplication().exit();
});
updateChart(hrmInfo.heartRate);
} else {
$('#textbox').html("No heart rate detected.");
}
}
This suppose to close application when pressing back button. However gear 2 has only one button. Is this button the tiwzenhwkey? For the hrm I am using the following code. For writing in file I am using:
function onsuccess(files) {
var testFile = null;
try{
testFile = documentsDir.createFile("test.txt");
if (testFile !== null) {
testFile.openStream(
"a",
function(fs){
fs.write(temp+"\n\n\n");
fs.close();
}, function(e){
console.log("Error " + e.message);
}, "UTF-8"
);
}
}
catch (e) { // file already exist -> append content
testFile = documentsDir.resolve('test.txt');
if(testFile !== null)
{
testFile.openStream(
"a",
function(fs){
fs.write(temp+"\n\n\n");
fs.close();
}, function(e){
console.log("Error " + e.message);
}, "UTF-8"
);
}
}
}
function onerror(error) {
console.log("The error " + error.message + " occurred when listing the files in the selected folder");
}
and
temp = heartrate;
tizen.filesystem.resolve(
'documents',
function(dir){
documentsDir = dir;
dir.listFiles(onsuccess,onerror);
}, function(e) {
console.log("Error" + e.message);
}, "a"
);
1. Create button in JS code
var b1 = document.createElement("BUTTON"); // Create Button
var b2 = document.createElement("BUTTON");
// Assign text to your button
b1.textContent = "Start";
b2.textContent = "Exit";
// Register click handlers to call respective functions
b1.onclick = function() {/*Code here*/};
b2.onclick = function() {/*Code here*/};
// Append them in your DOM i.e to show it on your page.
// Suppose to append it to an existing element in your page with id as "appp".
var attachTo = document.getElementById("appp");
attachTo.appendChild(b1);
attachTo.appendChild(b2);
2. TIZENHWKEY
On Gear, 'tizenhwkey' means "Swipe down" gesture and "Swipe UP" gesture.
Swipe Down acts as back key similar to how it works on phone. Swipe Up acts as menu button similar to how it works on phone
You can use below code to handle both the gestures I mentioned above.
document.addEventListener('tizenhwkey', function(e) {
if(e.keyName == "menu") {
}
if(e.keyName == "back") {
// you need to write exit statement
tizen.application.getCurrentApplication().exit();
}
}
Regarding HRM stop - use this to stop monitoring HRM.
webapis.motion.stop("HRM");
New line Issue - try this its working.
fs.write(temp + "\n\n\n");
I'm still a beginner but i know the basics on how to open a window and close it. Maybe this can help you.
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200, height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin(){
myWindow.close();
}

Js chess call sub function

My question is: How is it possible to call the function mova from outside the function init?
init.mova("a2-a3"); doesn't work
The full code is here.
This is a chessboard system.
I don't now how to call the function mova from outside init. init.mova doesn't work.
Code:
var init = function() {
//--- start example JS ---
var board,
game = new Chess(),
statusEl = $('#status'),
fenEl = $('#fen'),
pgnEl = $('#pgn');
// do not pick up pieces if the game is over
// only pick up pieces for the side to move
var onDragStart = function(source, piece, position, orientation) {
if (game.game_over() === true ||
(game.turn() === 'w' && piece.search(/^b/) !== -1) ||
(game.turn() === 'b' && piece.search(/^w/) !== -1)) {
return false;
}
};
var onDrop = function(source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a queen for example simplicity
});
if (move !== null) {
console.log(move.to);
}
// illegal move
if (move === null) return 'snapback';
updateStatus();
};
// update the board position after the piece snap
// for castling, en passant, pawn promotion
var onSnapEnd = function() {
board.position(game.fen());
};
var updateStatus = function() {
var status = '';
var moveColor = 'White';
if (game.turn() === 'b') {
moveColor = 'Black';
}
// checkmate?
if (game.in_checkmate() === true) {
status = 'Game over, ' + moveColor + ' is in checkmate.';
}
// draw?
else if (game.in_draw() === true) {
status = 'Game over, drawn position';
}
// game still on
else {
status = moveColor + ' to move';
// check?
if (game.in_check() === true) {
status += ', ' + moveColor + ' is in check';
}
}
statusEl.html(status);
fenEl.html(game.fen());
pgnEl.html(game.pgn());
};
var cfg = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
board = new ChessBoard('board', cfg);
updateStatus();
//--- end example JS ---
var mova = function(positie) {
board.move(positie);
}
}; // end init()
$(document).ready(init);
init.mova("a2-a3");
Variables defined within a function are scoped to that function. They cannot be called from outside of the function.
If you wanted a quick and dirty fix, you could define the variable mova outside the init() function, and then assign its value within it.
var mova;
var init = function() {
// etc. etc.
mova = function(positie) {
board.move(positie);
}
}
then, the mova function would be available outside of the init function once it has run.
You could ensure that you don't try to use the function until it's defined by using a function that is called when your init completes:
var mova;
var init = function() {
// etc. etc.
mova = function(positie) {
board.move(positie);
}
onInitComplete();
}
function onInitComplete() {
// function using mova function
}
It's likely, given the structure of your program, that you will want to use the same technique for many variables other than just mova. You probably don't want all of your game logic inside the init() function. You could define some variables for the state of your game outside the init function and then just assign them their starting values inside it. Hope that helps.

iCheck doesn't work ( strange behavior )

I want to use iCheck library:
https://github.com/fronteed/iCheck
http://fronteed.com/iCheck/
When i init the element with the library it get warped like the documentation describe https://github.com/fronteed/iCheck/#how-it-works but with opacity zero.
You can see it here: http://jsfiddle.net/buRq7/8/
$(".ex-f").iCheck();
somebody have the same issue?
Thanks
My code is:
/*!
* iCheck v1.0.1, http://git.io/arlzeA
* =================================
* Powerful jQuery and Zepto plugin for checkboxes and radio buttons customization
*
* (c) 2013 Damir Sultanov, http://fronteed.com
* MIT Licensed
*/
(function($) {
// Cached vars
var _iCheck = 'iCheck',
_iCheckHelper = _iCheck + '-helper',
_checkbox = 'checkbox',
_radio = 'radio',
_checked = 'checked',
_unchecked = 'un' + _checked,
_disabled = 'disabled',
_determinate = 'determinate',
_indeterminate = 'in' + _determinate,
_update = 'update',
_type = 'type',
_click = 'click',
_touch = 'touchbegin.i touchend.i',
_add = 'addClass',
_remove = 'removeClass',
_callback = 'trigger',
_label = 'label',
_cursor = 'cursor',
_mobile = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent);
// Plugin init
$.fn[_iCheck] = function(options, fire) {
// Walker
var handle = 'input[type="' + _checkbox + '"], input[type="' + _radio + '"]',
stack = $(),
walker = function(object) {
object.each(function() {
var self = $(this);
if (self.is(handle)) {
stack = stack.add(self);
} else {
stack = stack.add(self.find(handle));
};
});
};
// Check if we should operate with some method
if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(options)) {
// Normalize method's name
options = options.toLowerCase();
// Find checkboxes and radio buttons
walker(this);
return stack.each(function() {
var self = $(this);
if (options == 'destroy') {
tidy(self, 'ifDestroyed');
} else {
operate(self, true, options);
};
// Fire method's callback
if ($.isFunction(fire)) {
fire();
};
});
// Customization
} else if (typeof options == 'object' || !options) {
// Check if any options were passed
var settings = $.extend({
checkedClass: _checked,
disabledClass: _disabled,
indeterminateClass: _indeterminate,
labelHover: true,
aria: false
}, options),
selector = settings.handle,
hoverClass = settings.hoverClass || 'hover',
focusClass = settings.focusClass || 'focus',
activeClass = settings.activeClass || 'active',
labelHover = !!settings.labelHover,
labelHoverClass = settings.labelHoverClass || 'hover',
// Setup clickable area
area = ('' + settings.increaseArea).replace('%', '') | 0;
// Selector limit
if (selector == _checkbox || selector == _radio) {
handle = 'input[type="' + selector + '"]';
};
// Clickable area limit
if (area < -50) {
area = -50;
};
// Walk around the selector
walker(this);
return stack.each(function() {
var self = $(this);
// If already customized
tidy(self);
var node = this,
id = node.id,
// Layer styles
offset = -area + '%',
size = 100 + (area * 2) + '%',
layer = {
position: 'absolute',
top: offset,
left: offset,
display: 'block',
width: size,
height: size,
margin: 0,
padding: 0,
background: '#fff',
border: 0,
opacity: 0
},
// Choose how to hide input
hide = _mobile ? {
position: 'absolute',
visibility: 'hidden'
} : area ? layer : {
position: 'absolute',
opacity: 0
},
// Get proper class
className = node[_type] == _checkbox ? settings.checkboxClass || 'i' + _checkbox : settings.radioClass || 'i' + _radio,
// Find assigned labels
label = $(_label + '[for="' + id + '"]').add(self.closest(_label)),
// Check ARIA option
aria = !!settings.aria,
// Set ARIA placeholder
ariaID = _iCheck + '-' + Math.random().toString(36).replace('0.', ''),
// Parent & helper
parent = '<div class="' + className + '" ' + (aria ? 'role="' + node[_type] + '" ' : ''),
helper;
// Set ARIA "labelledby"
if (label.length && aria) {
label.each(function() {
parent += 'aria-labelledby="';
if (this.id) {
parent += this.id;
} else {
this.id = ariaID;
parent += ariaID;
}
parent += '"';
});
};
// Wrap input
parent = self.wrap(parent + '/>')[_callback]('ifCreated').parent().append(settings.insert);
// Layer addition
helper = $('<ins class="' + _iCheckHelper + '"/>').css(layer).appendTo(parent);
// Finalize customization
self.data(_iCheck, {o: settings, s: self.attr('style')}).css(hide);
!!settings.inheritClass && parent[_add](node.className || '');
!!settings.inheritID && id && parent.attr('id', _iCheck + '-' + id);
parent.css('position') == 'static' && parent.css('position', 'relative');
operate(self, true, _update);
// Label events
if (label.length) {
label.on(_click + '.i mouseover.i mouseout.i ' + _touch, function(event) {
var type = event[_type],
item = $(this);
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
if ($(event.target).is('a')) {
return;
}
operate(self, false, true);
// Hover state
} else if (labelHover) {
// mouseout|touchend
if (/ut|nd/.test(type)) {
parent[_remove](hoverClass);
item[_remove](labelHoverClass);
} else {
parent[_add](hoverClass);
item[_add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
};
// Input events
self.on(_click + '.i focus.i blur.i keyup.i keydown.i keypress.i', function(event) {
var type = event[_type],
key = event.keyCode;
// Click
if (type == _click) {
return false;
// Keydown
} else if (type == 'keydown' && key == 32) {
if (!(node[_type] == _radio && node[_checked])) {
if (node[_checked]) {
off(self, _checked);
} else {
on(self, _checked);
};
};
return false;
// Keyup
} else if (type == 'keyup' && node[_type] == _radio) {
!node[_checked] && on(self, _checked);
// Focus/blur
} else if (/us|ur/.test(type)) {
parent[type == 'blur' ? _remove : _add](focusClass);
};
});
// Helper events
helper.on(_click + ' mousedown mouseup mouseover mouseout ' + _touch, function(event) {
var type = event[_type],
// mousedown|mouseup
toggle = /wn|up/.test(type) ? activeClass : hoverClass;
// Do nothing if input is disabled
if (!node[_disabled]) {
// Click
if (type == _click) {
operate(self, false, true);
// Active and hover states
} else {
// State is on
if (/wn|er|in/.test(type)) {
// mousedown|mouseover|touchbegin
parent[_add](toggle);
// State is off
} else {
parent[_remove](toggle + ' ' + activeClass);
};
// Label hover
if (label.length && labelHover && toggle == hoverClass) {
// mouseout|touchend
label[/ut|nd/.test(type) ? _remove : _add](labelHoverClass);
};
};
if (_mobile) {
event.stopPropagation();
} else {
return false;
};
};
});
});
} else {
return this;
};
};
// Do something with inputs
function operate(input, direct, method) {
var node = input[0],
state = /er/.test(method) ? _indeterminate : /bl/.test(method) ? _disabled : _checked,
active = method == _update ? {
checked: node[_checked],
disabled: node[_disabled],
indeterminate: input.attr(_indeterminate) == 'true' || input.attr(_determinate) == 'false'
} : node[state];
// Check, disable or indeterminate
if (/^(ch|di|in)/.test(method) && !active) {
on(input, state);
// Uncheck, enable or determinate
} else if (/^(un|en|de)/.test(method) && active) {
off(input, state);
// Update
} else if (method == _update) {
// Handle states
for (var state in active) {
if (active[state]) {
on(input, state, true);
} else {
off(input, state, true);
};
};
} else if (!direct || method == 'toggle') {
// Helper or label was clicked
if (!direct) {
input[_callback]('ifClicked');
};
// Toggle checked state
if (active) {
if (node[_type] !== _radio) {
off(input, state);
};
} else {
on(input, state);
};
};
};
// Add checked, disabled or indeterminate state
function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
};
});
};
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
};
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
};
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
};
};
// Trigger callbacks
callbacks(input, checked, state, keep);
};
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
};
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'true') : parent.attr('aria-checked', indeterminate ? 'mixed' : 'true');
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
};
// Remove checked, disabled or indeterminate state
function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
};
// Trigger callbacks
callbacks(input, checked, callback, keep);
};
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
};
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
disabled ? parent.attr('aria-disabled', 'false') : parent.attr('aria-checked', 'false');
// Add regular state class
parent[_add](regular || option(input, callback) || '');
};
// Remove all traces
function tidy(input, callback) {
if (input.data(_iCheck)) {
// Remove everything except input
input.parent().html(input.attr('style', input.data(_iCheck).s || ''));
// Callback
if (callback) {
input[_callback](callback);
};
// Unbind events
input.off('.i').unwrap();
$(_label + '[for="' + input[0].id + '"]').add(input.closest(_label)).off('.i');
};
};
// Get some option
function option(input, state, regular) {
if (input.data(_iCheck)) {
return input.data(_iCheck).o[state + (regular ? '' : 'Class')];
};
};
// Capitalize some string
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
// Executable handlers
function callbacks(input, checked, callback, keep) {
if (!keep) {
if (checked) {
input[_callback]('ifToggled');
};
input[_callback]('ifChanged')[_callback]('if' + capitalize(callback));
};
};
})(window.jQuery || window.Zepto);
$(".ex-f").iCheck();
And
<div class="my-checkbox">
<input class="ex-f" id="Finish" name="Finish" type="checkbox" value="1"> doesn't work
</div>
And
.my-checkbox {
border: 1px solid blue;
height: 20px;
}
.ex-f {
border: 1px solid red;
}
I found that the problem was with the CSS file, if it is not loaded the component is not showed, a working example:
http://jsfiddle.net/SUTMf/1/
$(document).ready(function(){
$('input').iCheck({
checkboxClass: 'icheckbox_flat-blue',
radioClass: 'iradio_square',
increaseArea: '20%' // optional
});
});
today i encountered this problem. and the same problem.
but finally solved.
and the reason is:
my local golobal variable name is "_type" which maybe the keyword in iCheck or somethin' else .
when i have iCheck in my Html, i found that _type is already used as the picture showed
wish could help u and the others.
If you place it before the iCheck code, it works for me:
$(".ex-f").iCheck();
//iCheck function
Demo
Well, same thing happened to me, and the problem was a conflict with other javascript code included in the page. I removed it or changed it and it worked. I hope this could help somebody, I don't put the code in here because could be anything, just check your code just in case same thing is happening to you.

Categories