I have a large HTML table (1,000-1,500 rows, 40 cols wide). I have a few input and select boxes so users can filter rows. The relevant javascript/jquery (note: not entire code base is pasted in as it is not the bottleneck) attached to it looks like:
function autoRank() {
// auto number
rank = 0;
$("#myTablePlayers .playerData").each(function() {
if ($(this).css("display") != "none") {
rank++;
$(this).find('td').eq(colRank).text(rank);
}
});
}
var teamCols = $(),
GPCols = $(),
posCols = $(),
ageCols = $();
$("#myTablePlayers .playerData").each(function() {
var columns = $(this).find('td');
teamCols = teamCols.add($(".colTeam", this));
GPCols = GPCols.add(columns.eq(colGP));
posCols = posCols.add(columns.eq(colPos));
ageCols = ageCols.add(columns.eq(colAge))
});
function filterTable() {
// Need some error checking on input not number
minGP = $("#mingp").val()
teams = $("#teamFilter").val().toUpperCase()
position = $("#position").val()
age = $("#age").val()
$("#myTablePlayers .playerData").show();
/* Loop through to check for teams */
if (teams) {
teamCols.each(function() {
if (!this.innerHTML.toUpperCase().includes(teams)) {
$(this).parent().hide();
}
});
}
/* Loop and check for min GP */
GPCols.each(function() {
if ( Number(this.innerHTML) < minGP) {
$(this).parent().hide();
}
});
/* Check for age requirement */
if (age) {
age = Number(age)
ageCols.each(function() {
thisAge = Number(this.innerHTML);
if ( thisAge < age || thisAge >= age+1 ) {
$(this).parent().hide();
}
});
}
/* Check the position requirement */
if (position) {
posCols.each(function() {
var thisPos = this.innerHTML
if (position == "D") {
if (thisPos.indexOf("D") == -1) {
$(this).parent().hide();
}
} else if (position == "F") {
if (thisPos.indexOf("D") != -1) {
$(this).parent().hide();
}
} else if (thisPos != position) {
$(this).parent().hide();
}
});
}
autoRank();
}
When stripping down the code as minimal as possible, the offending code is the
var.each(function() { ...
in the filterTable() function.
When I run this on Chrome or Firefox it runs quickly (sub 1 second) and the DOM is rendered properly. When I execute on Safari it takes 30+ seconds.
Why is this and what can I do to adapt for this browser?
jQuery: 1.11.1 (same issue even after upgrading to 3.1.1).
Safari: 10.0.1
Firefox: 50
Chrome: 54.0.
After removing all the repetition and unnecessary complication from your code, this is what remains:
var colRank = 0, colTeam = 1, colGP = 2, colAge = 3, colPos = 4;
function filterTable() {
var minGP = +$("#mingp").val();
var age = +$("#age").val();
var teams = $("#teamFilter").val().toUpperCase();
var position = $("#position").val();
var rank = 0;
$("#myTablePlayers .playerData").each(function () {
if (
(teams && this.cells[colTeam].textContent.toUpperCase().includes(teams)) ||
(minGP && +this.cells[colGP].textContent < minGP) ||
(age && (+this.cells[colAge].textContent < age || +this.cells[colAge].textContent >= age+1)) ||
((position === "D" || position === "F") && this.cells[colPos].textContent.indexOf(position) === -1) ||
(!(position === "D" || position === "F") && (this.cells[colPos].textContent !== position))
) {
this.cells[colRank].textContent = ++rank;
this.style.display = "";
} else {
this.style.display = "none";
}
});
}
I've already removed almost all jQuery in favor of native DOM manipulation.
The remaining .each() could be tuned into a plain old for loop over the document.getElementById('myTablePlayers').tBodies[0].rows, if you want to squeeze out the last bit of possible performance.
Reorder the if conditions by likeliness: From the one that will typically filter out the most rows to the one that will filter out the least rows. Because JS short-circuits conditions, this way less conditions are checked overall.
Making the table display: fixed can also improve render performance at the expense of flexibility.
Finally, you can use CSS to do counters. This is probably faster than manually setting the contents of a table cell. Test for yourself.
Related
I have a simple JQuery/JS Hangman game and I've spent alot of time making it work and I've run into one issue that messes up my logic and running of the game - when the player enters repeated chars (either right or wrong).
The way I've made the game work, starting with empty arrays I'm pushing into, I thought that I could create a function to only push unique chars into the array function
unique(array) {
var result = [];
$.each(array, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
var uniqueRightGuesses = unique(rightGuesses);
var uniqueWrongGuesses = unique(wrongGuesses);
But this doesn't work because w/the inner workings of my game, the repeated input chars are still getting displayed & messing up the way winning & loosing is input (even though I'm calculating winning w/the sum of an additional array I've created to take care of a letter that repeats multiple times in a word). I've tried alot of various things at various parts of the game/in various functions and I've figured out that the easiest way to take care of this issue would be to somehow prevent the player from inputing a char if they've already input in the course of the game, in this function:
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
play(space);
$(this).val('');
endGame();
return false;
}
});
I've searched online for a way to do this, I've found jQuery.unique() but I don't think that it'd work here as it's only on DOM objects in an array (& I just want the input to not register/not be allowed if the player has already entered that letter, if it's right or wrong guess- if I take care of this problem at this spot in the game, I won't have to mess w/my arrays or the variables I'm displaying but I don't know how to simply do this.
If anyone has any suggestions or knows if this is even possible, I'd really appreciate it- I've found alot online about restricting special chars & numbers in this way but nothing about ones that have already been entered & I don't know if this is even possible (this is the first time I've ever even used .keypress() so I'm sort of new to it. Any suggestions would be much appreciated. Thanks!
Here's my entire game code:
var wordBank = ["modernism", "situationalist", "sartre", "camus", "hegel", "lacan", "barthes", "baudrillard", "foucault", "debord", "baudrillard"];
var word = [];
var answer = [];
var wrongGuesses = [];
var rightGuesses = [];
var right = [];
var images = [gallows, head, body, armL, handL, armR, handR, legL, footL, legR, footR];
var y = 0;
var i = 1;
$(document).ready(function() {
function randomWord() {
var random = Math.floor(Math.random() * wordBank.length);
var toString = wordBank[random];
console.log(toString);
word = toString.split("");
console.log(word);
}
randomWord();
function wordSpaces() {
for (var i = 0; i < word.length; i++) {
$(".word-spaces > tbody > tr").append('<td data-idx=i>' + word[i] + '</td>')
}
}
wordSpaces();
function play(space) {
//indexOf()==inArray()
var rightCount = 0;
var lIndex = jQuery.inArray(space, word);
console.log(lIndex);
if (lIndex == -1) {
wrongGuesses.push(space);
var wrong = wrongGuesses.length;
console.log('wrong ' + wrong);
$('.wrongLetters tbody tr td:nth-of-type(' + wrong + ')').text(space);
// $(this).css("background-color", "#ff4500").fadeIn(300).delay(800).fadeOut(300);
$(images[i - 1]).hide();
$(images[i]).show();
i++;
$("html").css("background-color", "#ff4500").fadeIn(300).delay(300).fadeOut(300).fadeIn(100);
console.log(word);
} else {
var totalRight = 0;
console.log(word + "word");
console.log(space + "space");
function getInstances(word, space) {
var indexes = [],
w;
for (w = 0; w < word.length; w++)
if (word[w] === space)
indexes.push(w);
return indexes;
}
console.log(word + "word");
console.log(space + "space");
var indexes = getInstances(word, space);
console.log("indexes", indexes);
indexes.forEach(function(index) {
// answer[index] = space;
rightCount++
});
console.log(rightCount + "rightcount");
console.log("answer", answer);
// rightGuesses.push(space);
console.log(rightGuesses);
// var right = rightGuesses.length;
indexes.forEach(function(index) {
$(".word-spaces tbody tr td:nth-of-type(" + (index + 1) + ")").css('color', 'black');
});
rightGuesses.push(space);
right.push(rightCount);
console.log(right + "right");
// rightGuesses.push(space);
// totalRight = totalRight + rightCount;
// totalRight++;
// console.log(totalRight + 'totalRight');
}
}
console.log(right + "right");
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
play(space);
$(this).val('');
endGame();
return false;
}
});
function endGame() {
var sumRight = right.reduce(add, 0);
function add(a, b) {
return a + b;
}
if (sumRight == word.length) {
$(images[i]).hide();
$("#victory").show();
$("body").css("background-color", "#8AFBFF");
$(".form-control").prop('disabled', true);
$("body").animate({
backgroundColor: "#0C0D86"
}, 2000);
$("body").animate({
backgroundColor: "transparent"
}, 2000);
} else if (wrongGuesses.length >= 10) {
$("body").css("background-color", "#ff4500");
$(".form-control").prop('disabled', true);
$("body").animate({
backgroundColor: "#000000"
}, 2000);
$("body").animate({
backgroundColor: "transparent"
}, 2000);
}
}
});
Use Array.indexOf(). No need for jQuery.
Do a check to see if the key pressed is contained in the wrongGuess or rightGuess array and if it is alert the user.
$(".form-control").keypress(function(event) {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == 13) {
var space = $(this).val().toLowerCase();
if (!(wrongGuess.indexOf(space) > -1 || rightGuess.indexOf(space) > -1)) {
play(space);
$(this).val('');
endGame();
return false;
}
else
window.alert("You already guessed this letter.");
}
});
I need to fire an event after my combo box finishes its filter
I have extended the widget and have tried to chuck a .done on the end of the call.
search: function(word) {
word = typeof word === "string" ? word : this.text();
var that = this,
length = word.length,
options = that.options,
ignoreCase = options.ignoreCase,
filter = options.filter,
field = options.dataTextField;
clearTimeout(that._typing);
if (length >= options.minLength) {
that._state = STATE_FILTER;
if (filter === "none") {
that._filter(word);
} else {
that._open = true;
that._filterSource({
value: ignoreCase ? word.toLowerCase() : word,
field: field,
operator: filter,
ignoreCase: ignoreCase
}); // .done here does not work :(
}
}
},
I need to know when a value is returned so that I can do some other stuff on my page once i know that the input matches a value server side.
Can anybody think of a way to achieve this? :)
Is there a way to fire an event once the datasource has changed?
I solved the issue by using the _busy state on the widget.
The following code is in the select function on the widget so whenever someone losses focus this fires.
If the widget is not busy it will have finished the ajax call.
Hope this is usefull to someone :)
if (data && data.length != 0)
{
for (var i = 0; i < data.length; i++)
{
li = $(that.ul).find('li:nth-child(' + (i + 1) + ')');
if (li.length != 0 && data[i].ProductCode == that.input.val())
{
that._select(li);
return;
}
}
}
if (that._busy && that._busy != null)
{
that.busyCheck = setInterval(function () {
if (!that._busy || that._busy == null) {
clearInterval(that.busyCheck);
if (data && data.length != 0){
for (var i = 0; i < data.length; i++){
li = $(that.ul).find('li:nth-child(' + (i + 1) + ')');
if (li.length != 0 && data[i].ProductCode == that.input.val()){
that._select(li);
return;
}
}
}
}
}, 50);
}
that._AddcodeIsServerValid(false);
All,
I have three cards which can be shuffled by the user, upon hover, the target card pops to the top, the last card on top should sit in the second position. While with the code below, I can have this effect in one direction (left to right), I am struggling to come up with logic & code for getting the effect to work in both directions without having to write multiple scenarios in js (which doesnt sound like very good logic).
Hopefully the demo will do a better explanation.
Code:
$(".cBBTemplates").on (
{
hover: function (e)
{
var aBBTemplates = document.getElementsByClassName ("cBBTemplates");
var i = 2;
while (i < aBBTemplates.length && i >= 0)
{
var eCurVar = aBBTemplates[i];
if (eCurVar === e.target)
{
eCurVar.style.zIndex = 3;
} else if (eCurVar.style.zIndex === 3) {
console.log (eCurVar);
eCurVar.style.zIndex = 3-1;
} else
{
eCurVar.style.zIndex = i;
}
i--;
}
}
});
Try this:
$(function(){
var current = 2;
$(".cBBTemplates").on (
{
hover: function ()
{
var target = this,
newCurrent, templates = $(".cBBTemplates");
templates.each(
function(idx){
if(this === target){
newCurrent = idx;
}
});
if(newCurrent === current){return;}
templates.each(function(index){
var zIndex = 0;
if(this === target) {
zIndex = 2;
}
else if (index == current) {
zIndex = 1;
}
$(this).css('zIndex', zIndex);
});
current = newCurrent;
}
});
});
I have encountered a strange behavior on android browser / webview. I was testing an input that will automatically format to phone number format "(xxx) xxx-xxxx". But then what happened was when I tapped or press any number on androids keyboard, the first input was like this "(x" but then the cursor was in between "(" and "x". Is there a way to put the cursor after "x" value?
I tested this on iPhone and windows web browsers and it works fine. Please let me know if there are mistakes on my jquery or javascripts.
Thanks
HTML CODE:
<html>
<head>
<title>Sample Phone Number Format</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<input type="text" id="phone" />
<script type="text/javascript">
$('#phone').on('keydown', function (event) {
objval = $(this).val();
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || (objval.length > 13))) {
event.preventDefault();
} else {
if (objval.length == 0) {
$(this).val(objval + '(');
alert(objval + '(');
} else if (objval.length == 4) {
$(this).val(objval + ') ');
alert(objval + ') ');
} else if (objval.length == 9) {
$(this).val(objval + '-');
alert(objval + '-');
} else if (objval.length >= 14) {
if (event.keyCode == 9) {
return;
} else {
event.preventDefault();
}
}
}
}
});
$('#phone').on('keydown', function (event) {
var objVal = $(this).val();
if(objVal.length < 14)
{
validateCallerForm(objVal + String.fromCharCode((96 <= event.keyCode && event.keyCode <= 105)? event.keyCode-48 : event.keyCode));
}
});
//Validates proper phone format, true if valid phone number, false otherwise
function isValidPhoneNumber(elementValue) {
var numberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return numberPattern.test(elementValue);
}
//validates entire caller form, also updates css classes for proper response
function validateCallerForm(PhoneNumber) {
if (isValidPhoneNumber(PhoneNumber)) {
alert("true");
} else {
alert("false");
}
}
</script>
</body>
</html>
Giving +50 Bounty to who'm will answer this correctly
you have to first define listener for typing and copy-paste like below (not required) :
$("#phone").keyup( function() {
maskLine(this);
});
$("#phone").change( function() {
maskLine(this);
});
Then, to manage cursor placement, you have to cache previous phone number and then, you could compare difference and update cursor position if needed.
So declare, you have to declare a global array like this :
var _cacheElementValues = new Array();
At last, you can check the function below, it applies your mask to phone number field and manage cursor placement :
function maskLine( element ) {
element = $(element);
var maskedLine = '';
var line = element.attr('value');
// check the cache of the input and abord if no change since last treatment
if (_cacheElementValues[element.attr('id')] != undefined && _cacheElementValues[element.attr('id')] == line) {
return;
}
line = line.replace(/\D/g, ''); // remove all characters != digits
line = line.substring(0, 10);
if (line != '') {
// apply mask
if (line.length <= 2 ) {
maskedLine = "(" + line;
} else if (line.length < 6) {
maskedLine = line.replace(/^([0-9]{3})([0-9]{0,3})/g, '($1) $2');
} else {
// mask : '(XXX) XXX-XXXX'
maskedLine = line.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})/g, '($1) $2-$3');
}
}
// define cursor position at the end of the input by default
var pos = maskedLine.length;
// Change cursor placement if necessary
if (typeof element[0].selectionStart != 'undefined') {
var start = element[0].selectionStart;
var end = element[0].selectionEnd;
var insText = element[0].value.substring(start, end);
// get current cursor placement
if (insText.length == 0) {
pos = start;
} else {
pos = start + insText.length;
}
// find how many digits typing since last mask application
var previousLength = 0;
if (_cacheElementValues[element.attr('id')] != undefined) {
previousLength = _cacheElementValues[element.attr('id')].replace(/\s/g, '').length;
}
var diff = maskedLine.replace(/\s/g, '').length - previousLength;
// if sum of new typing digit is > 0 : we change cursor placement
if (diff > 0) {
pos += (diff - 1) + Math.round((diff-1)/3);
if (pos%6 == 0 && maskedLine.length >= pos+1) pos++;
}
}
// update input data & cache
element.val(maskedLine);
_cacheElementValues[element.attr('id')] = maskedLine;
// update cursor placement
element[0].selectionStart = element[0].selectionEnd = pos;
}
You can find this example on jsFiddle : http://jsfiddle.net/UE9LB/5/
I hope this little explantion can solve your problem ;)
Enjoy !
ps: i apologize for my poor english :s
I'd recommend at least starting with an existing plugin rather than going through your own isolated rounds of solving issues.
http://digitalbush.com/projects/masked-input-plugin/
https://github.com/igorescobar/jQuery-Mask-Plugin
The short answer is to set the selectionStart and selectionEnd properties of the input element. After you format the value, set these properties to this.value.length.
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
But, where you are going to run into trouble is when the cursor is not at the end of the text. Eg, the user has manually positioned the cursor to a position within the text. To prevent the cursor from jumping to the end, you will need to detect the cursor position before you format the input, then put the cursor back in the appropriate position after formatting.
Edit: This jsFiddle may get you started, but isn't perfect yet.
I rewrite the code on my #phone keydown event and this will work on iPhone, Android, webkit browsers.
$('#phone').on('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
// ignore if BKSPCE, left arrow, or right arrow
} else {
// validate if anything else
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,10);
var string = ("(" + first3 + ") " + next3 + "-" + next4);
$(this).val(string);
}
});
At the url http://www.candyundies.com/template_non_product.php, I am using an autocomplete script on the search box for suggestions. I have tested and is working in current versions of Chrome, Safari, Opera, Firefox and IE 8. However, I noticed in IE 8, it is throwing an Object expected error after the first letter is typed in the search box but the script continues to work flawlessly. I'm sure it is a syntax error or something small I have overlooked but I cannot seem to find the problem. Any help would be much appreciated.
Contents of autocomplete.js:
// global variables
var acListTotal = 0;
var acListCurrent = -1;
var acDelay = 100;
var acURL = null;
var acSearchId = null;
var acResultsId = null;
var acSearchField = null;
var acResultsDiv = null;
function setAutoComplete(field_id, results_id, get_url) {
// initialize vars
acSearchId = "#" + field_id;
acResultsId = "#" + results_id;
acURL = get_url;
// create the results div
$("#auto").append('<div id="' + results_id + '"></div>');
// register mostly used vars
acSearchField = $(acSearchId);
acResultsDiv = $(acResultsId);
// on blur listener
acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 100) });
// on key up listener
acSearchField.keyup(function (e) {
// get keyCode (window.event is for IE)
var keyCode = e.keyCode || window.event.keyCode;
var lastVal = acSearchField.val();
// check an treat up and down arrows
if(updownArrow(keyCode)){
return;
}
// check for an ENTER or ESC
if(keyCode == 13 || keyCode == 27){
clearAutoComplete();
return;
}
// if is text, call with delay
setTimeout(function () {autoComplete(lastVal)}, acDelay);
});
}
// treat the auto-complete action (delayed function)
function autoComplete(lastValue) {
// get the field value
var part = acSearchField.val();
// if it's empty clear the resuts box and return
if(part == ''){
clearAutoComplete();
return;
}
// if it's equal the value from the time of the call, allow
if(lastValue != part){
return;
}
// get remote data as JSON
$.getJSON(acURL + part, function(json){
// get the total of results
var ansLength = acListTotal = json.length;
// if there are results populate the results div
if(ansLength > 0){
var newData = '';
// create a div for each result
for(i=0; i < ansLength; i++) {
newData += '<div class="unselected">' + json[i] + '</div>';
}
// update the results div
acResultsDiv.html(newData);
acResultsDiv.css("display","block");
// for all divs in results
var divs = $(acResultsId + " > div");
// on mouse over clean previous selected and set a new one
divs.mouseover( function() {
divs.each(function(){ this.className = "unselected"; });
this.className = "selected";
});
// on click copy the result text to the search field and hide
divs.click( function() {
acSearchField.val(this.childNodes[0].nodeValue);
clearAutoComplete();
});
} else {
clearAutoComplete();
}
});
}
// clear auto complete box
function clearAutoComplete() {
acResultsDiv.html('');
acResultsDiv.css("display","none");
}
// treat up and down key strokes defining the next selected element
function updownArrow(keyCode) {
if(keyCode == 40 || keyCode == 38){
if(keyCode == 38){ // keyUp
if(acListCurrent == 0 || acListCurrent == -1){
acListCurrent = acListTotal-1;
}else{
acListCurrent--;
}
} else { // keyDown
if(acListCurrent == acListTotal-1){
acListCurrent = 0;
}else {
acListCurrent++;
}
}
// loop through each result div applying the correct style
acResultsDiv.children().each(function(i){
if(i == acListCurrent){
acSearchField.val(this.childNodes[0].nodeValue);
this.className = "selected";
} else {
this.className = "unselected";
}
});
return true;
} else {
// reset
acListCurrent = -1;
return false;
}
}
Issue resolved. See comment by ocanal.