Unexpected behavior in simple jquery selector script - javascript

EDIT: If anyone, ever need this script for some reason, i made a cleaner fully working version: https://jsfiddle.net/qmgob1d5/3/
I have a jquery script that is supposed to highlight elements in a from-to manner. It should work backwards as well.
Here is working fiddle: https://jsfiddle.net/qmgob1d5/
It works fine, until I select zero (first box) as second element. Then the var Start = Math.min(ClickOne, ClickTwo || 16); doesn't seems to work as expected. What went wrong?
Here is the script:
var FirstClick;
var ClickOne;
var ClickTwo;
$('.ColorPreview').on('click',function() {
var ColorId = $(this).attr('id');
ColorId = Number(ColorId.split('_')[1]);
if (!FirstClick) {
//reset function
for (var i = 0; i < 16; i++) {
$('#Color_' + i).removeClass('SelectColor'); }
var ClickTwo;
ClickOne = ColorId;
FirstClick = true;
}
else {
ClickTwo = ColorId;
FirstClick = false; }
console.log('ClickOne ' + ClickOne)
console.log('Clicktwo ' + ClickTwo)
var Start = Math.min(ClickOne, ClickTwo || 16);
var End = Math.max(ClickOne, ClickTwo || 0);
console.log('start ' + Start)
console.log('end ' + End)
for (var i = Start; i <= End; i++) {
$('#Color_' + i).addClass('SelectColor'); }
});

When ClickTwo is 0, the expression ClickTwo || 16 will evaluate to 16.
Try
var Start = Math.min(ClickOne, ClickTwo == null ? 16 : ClickTwo);
Or else initialize ClickTwo to 16 at the beginning of the function.

Related

website breaks when running this function

I have the following function:
function Test() {
var x = document.getElementById("input").value;
var res = "";
var c = 1;
var stoc = "";
while (x > 0) {
var help = c.toString();
var h = help.length;
while (h > 0) {
res += help[h - 1];
h--;
}
if (res === help) {
stoc += res + ";" + " ";
x--;
}
c++;
}
document.getElementById("stoc").innerHTML = stoc;
}
Whenever i trigger the function the button stays pushed and the site stops responding. The algorithm is supposed to return the first x polindrom (that are written the same way from right to left ex 121) numbers.
Your browser is crashing because x is never getting decremented causing the loop to never exit. Check the value of help in the debugger.

Superscripts and subscripts in HTML input

I am making a small JavaScript web app that deals with chemical formulas, so I need to allow users to input superscripts. The easiest thing for users would be having the text editor switch to superscript when they press ^. How can I do this with an HTML textarea?
Borrowing from the function in adeneo's answer
Check this fiddle here : fiddle
Usage : To type a superscript , press ^ --> type in the superscript --> press Esc , the superscript will then appear in the textarea.
$(document).ready(function() {
var temp = {}; // store keypresses here
var current_value = "";
$("#text_area").keydown(function(e) {
temp[e.which] = true;
});
$('#text_area').keyup(function(e) {
if (e.keyCode == 27 && current_value != "") {
var length_1 = current_value.length;
var length_without_sup = length_1 - 5;
var substr_superstring = $('#text_area').val().substr(length_without_sup);
var current_text_2 = current_value + substr_superstring;
current_text_2 = current_text_2 + "</sup>";
$('#text_area').val(current_text_2);
$('#text_area').superScript();
}
var flag_shift = false;
var flag_super = false;
for (var key in temp) {
if (key == 16) {
flag_shift = true;
} else if (key == 54) {
flag_super = true;
}
}
if (flag_shift == true && flag_super == true) {
var current_text = $('#text_area').val();
current_text_2 = current_text.substr(0, current_text.length - 1);
current_text_2 = current_text_2 + "<sup>";
$('#text_area').val(current_text_2);
current_value = hide_superscript_tag();
}
delete temp[e.which];
});
});
function hide_superscript_tag() {
var current_value = $('#text_area').val();
current_value_2 = current_value.substr(0, current_value.length - 5);
$('#text_area').val(current_value_2);
return current_value;
}
$.fn.superScript = function() {
var chars = '+−=()0123456789AaÆᴂɐɑɒBbcɕDdðEeƎəɛɜɜfGgɡɣhHɦIiɪɨᵻɩjJʝɟKklLʟᶅɭMmɱNnɴɲɳŋOoɔᴖᴗɵȢPpɸqrRɹɻʁsʂʃTtƫUuᴜᴝʉɥɯɰʊvVʋʌwWxyzʐʑʒꝯᴥβγδθφχнნʕⵡ',
sup = '⁺⁻⁼⁽⁾⁰¹²³⁴⁵⁶⁷⁸⁹ᴬᵃᴭᵆᵄᵅᶛᴮᵇᶜᶝᴰᵈᶞᴱᵉᴲᵊᵋᶟᵌᶠᴳᵍᶢˠʰᴴʱᴵⁱᶦᶤᶧᶥʲᴶᶨᶡᴷᵏˡᴸᶫᶪᶩᴹᵐᶬᴺⁿᶰᶮᶯᵑᴼᵒᵓᵔᵕᶱᴽᴾᵖᶲqʳᴿʴʵʶˢᶳᶴᵀᵗᶵᵁᵘᶸᵙᶶᶣᵚᶭᶷᵛⱽᶹᶺʷᵂˣʸᶻᶼᶽᶾꝰᵜᵝᵞᵟᶿᵠᵡᵸჼˤⵯ';
return this.each(function() {
this.value = this.value.replace(/<sup[^>]*>(.*?)<\/sup>/g, function(x) {
var str = '',
txt = $.trim($(x).unwrap().text());
for (var i = 0; i < txt.length; i++) {
var n = chars.indexOf(txt[i]);
str += (n != -1 ? sup[n] : txt[i]);
}
return str;
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="text_area">
</textarea>
I would recommend leveraging an existing solution. Take a look at MathQuill.
Regarding creating your own such system from scratch, there is no simple solution. You would need to do independent research and experimentation and return to Stack Overflow with more specific questions.

Show modal and wait for action for each element while looping

I'm looking for simple solution for a loop where I have to confirm each element. I was looking at pausing and resuming, but it's quite a hassle. Is there any other way to make it easy? I'm sure that this problem is not so rare and many people have stuck upon it.
What I want to achieve is this - I'm looping through the list and if I don't find item by its EAN code then it opens search function to find this and after the item is found (or not) user clicks Next and resume with looping until same situation occurs.
Some code that I have for now:
for(var f = 0; f < biLen; f++){
var ean_parsed = parsedList[i][1];
if(beerList[f].get("ean") === ean_parsed){
console.log("Beer found: " + beerList[f].get("beer_name"));
break;
} else {
if(f === biLen - 1){
//open modal, search for item and then continue looping
console.log("B'r not found: " + parsedList[i][0]);
}
}
}
edit (whole function code instead of piece of it):
function parserCompareList(){
var parsedList = parseResult;
var piLen = parsedList.length;
var beerList = listaPiwArr;
var biLen = beerList.length;
var new_offer = [];
var counter = document.getElementById('imHeader');
for(var i = 0; i < piLen; i++){
counter.innerHTML = i + "/" + piLen; //plain text that's keeping where we actually are with this
for(var f = 0; f < biLen; f++){
var ean_parsed = parsedList[i][1];
if(beerList[f].get("ean") === ean_parsed){
console.log("Beer found: " + beerList[f].get("beer_name"));
break;
} else {
if(f === biLen - 1){
console.log("B'r not found: " + parsedList[i][0]);
}
}
}
}
}
ANSWER:
var indexCache;
function loop() {
var index = indexCache || 0;
for (var f = index; f < biLen; f++) {
var ean_parsed = parsedList[i][1];
if (beerList[f].get("ean") === ean_parsed) {
console.log("Beer found: " + beerList[f].get("beer_name"));
break;
} else {
if (f === biLen - 1) {
// Assuming $modal is the bootstrap modal
indexCache = f;
//$modal.modal().one('hide.bs.modal', loop);
$('#importModal').modal('show').one('hidden.bs.modal', loop) // <-- this one works like a charm
return;
}
}
}
}
loop();
var indexCache;
function loop() {
var index = indexCache || 0;
for (var f = index; f < biLen; f++) {
var ean_parsed = parsedList[i][1];
if (beerList[f].get("ean") === ean_parsed) {
console.log("Beer found: " + beerList[f].get("beer_name"));
break;
} else {
if (f === biLen - 1) {
// Assuming $modal is the bootstrap modal
indexCache = f;
$modal.modal().one('hide.bs.modal', loop);
return;
}
}
}
}
loop();
We have an indexCache variable that holds the index of the beer that is being handled.
If EAN is found, great! we handle it and move on to the next beer.
If not, we store the current beer index in the cache and show the modal and quit the loop immediately. When the modal is hidden, the loop resumes from the cached index.
PS. I am assuming you are using Twitter Bootstrap modal. And therefore, adding a handler to the event 'hide.bs.modal'. But similar thing could be done with your own modal implementation if that is the case.

I'm using raphael.js for a visual interface on my Battleship game. I'm having some problems

I'm using raphael.js as a visual interface of my Battleship game. I have a function called createCanvas() which creates a grid (10x10). That way the user can see where to aim. The problem is, the grid doesn't appear until after the code of the game (putting in coordinates etc) has finished. Anyone know how to solve this?
Here's the entire code. Below, the code of createCanvas() and of game().
function createCanvas() {
$(function() {
var canvas = Raphael(0, 0, 2000, 2000);
for(var i = 0; i != (BOARD_WIDTH); i++) {
canvas.text((60+70*i), 15, i+1);
}
for(var i = 0; i != (BOARD_HEIGHT); i++) {
canvas.text(15, (60+70*i), i+1);
}
for(var i = 0; i != (BOARD_WIDTH+1); i++) {
canvas.path( "M" + (25+(70*i)) + ",25 L" + (25 + (70*i)) + ",725" );
}
for(var i = 0; i != (BOARD_HEIGHT+1); i++) {
canvas.path( "M25," + (25+(70*i)) + " L725," + (25+(70*i)) );
}
});
}
function game(){
inputArray = [4,3,2];
var boats = randomBoats(inputArray);
var currentBoat = 0;
var sunkenBoat = 0;
var numberOfTurns = 0;
while(sunkenBoat !== inputArray.length ) {
var hit= false;
var target = "(" + prompt("Enter targetcoordinate (x,y)") + ")";
var targetString = target.replace(/\s+/g, '');
for(var i = 0; i !== inputArray.length; i++) {
for(var j = 0; j !== boats[i].usedPositions().length; j++) {
console.log(targetString)
if(targetString === boats[i].usedPositions()[j].toString()) {
hit = true;
boats[i].hits[j] = 1;
console.log(boats[i].hits);
currentBoat = boats[i];
fillSquare(targetString, "red");
break;
}
}
}
console.log(currentBoat.hits);
console.log(allEquals(currentBoat.hits, 1));
if(hit)
alert ("Hit!");
else {
fillSquare(targetString, "blue");
alert ("Miss!");
}
if(allEquals(currentBoat.hits, 1)) {
alert("Boat with length " + currentBoat.hits.length + " has sunken!");
sunkenBoat++;
}
numberOfTurns++
}
alert("You've won! You did it in " + numberOfTurns + " turns.")
}
In my code I call
createCanvas();
game();
so I would think the canvas is drawn first...
The issue is the While loop. You're not giving anything else a chance to get in and do anything. This will just keep going around and around as fast as possible until you're done.
You should take a stab at putting a Input box on the page and and detecting key events looking for the enter key with something like this.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
That way the animations and other stuff your're going to need later can run without being blocked, you don't burn CPU cycles like crazy, and you only check for a hit when the user has actually entered a value
Then you will maybe even write some code display "Hit" or "Miss" on canvas (may be animated) and that way you can remove all the alert and message boxes that keep popping up.

javascript textarea character limit per line

I have a textarea with limited characters per line. Its function fine.
function limitRow(){
var count = 1;
var charsPerLine = row; // 30 characters
var maxLines = 20;
$('.AD_Text_textarea').keydown(function (e) {
var v = $(this).val(),
vl = v.replace(/(\r\n|\n|\r)/gm, '').length,
lineCount = $(this).val().split("\n").length;
if (parseInt(vl / count) >= charsPerLine) {
if (lineCount >= maxLines) {
return false;
}
$(this).val(v + "\n");
count += 1;
}
});
}
My question is, if Iam going to line 1, after typing for example 4 rows text and type on for example cursor position 4 some text, then the line counter counts of the beginning and breaks the line after 60 characters and jumps on the end of line 4.
How can I resolve this problem?
I hope, it was clear. (Iam sorry for my english)
try this
var count = 1;
var charsPerLine = 30; // 30 characters
var maxLines = 2;
$('.AD_Text_textarea').keydown(function (e) {
var this_input = $(this);
var value = this_input.val().split('\n');
if (value.length < maxLines) {
if (value[parseInt(value.length) - 1].toString().length > charsPerLine) {
alert(value.length.toString());
this_input.val(this_input.val() + '\n');
}
}
else {
return false;
}
});

Categories