Convert .each() because it's slow - javascript

I'm using the .each function to hide/show columns of a table. But the problem is that the code is very slow in IE. After searching on internet I saw that could be because of my .each() function and $(this).
For more information why I'm using this code, you can look at this post: Hide/show column
This is my old code:
include JQuery.min.js on page
javascript:
$(function () {
$('table th').each(function (_id, _value) {
if(_id > 2){
if($(this).find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($(this).find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
});
});
HTML:
<div id="togglers">Show/Hide columns<br/></div>
I tried to convert my javascript with this code (Source: jQuery very slow in IE), but I think there is still a problem with my i(or _id) and _value...
$(function () {
var items = $('table th');
var $currentItem;
for (var i = 0, j = items.length; i < j; i++) {
$currentItem = $(items[i]); // in place of $(this)
function (i, _value) {
if(i > 2){
if($currentItem.find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($currentItem.find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
}
}
});
It's possible that I need to use other code. Any suggestion is welcome! Tnx.

Performance issue has nothing to do with .each. DOM is tens of times slower than any way to iterate collection you choose.
Instead of iterating table on every toggle you can make CSS do it for you. Demo.
$(function() {
var togglers = $('#togglers'), //cache toggler ref
addToggler = function(idx, text) {
togglers.append('<span class="toggler" data-id="'
+ idx + '">' + text + '</span>');
},
table = $('#table'), //cache table ref
columns = 0;
//generate styles for 100 columns table :)
(function generateStyleSheet(len){
var styles = [], i = 0;
for(; i < len; i++) {
styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
}
$('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))
//bind on click once using event delegation
togglers.on('click', '.toggler', function(e){
var id = $(e.target).toggleClass('pressed').data('id');
table.toggleClass('hide-' + id);
});
//generate all togglers and count em
table.find('th').each(function(idx, header){
header = $(header);
addToggler(idx, header.text()); //make toggler
header.addClass('column-' + idx); //add class column-i
columns++;
});
//add column-i class to tds
table.find('td').each(function(idx, td) {
$(td).addClass('column-' + (idx%columns));
});
});

Related

Get Checked count in dynamic check boxes JavaScript

I'm using following code to design my screen dynamically according to the DB data.
function RefillUI(data) {
var html = "";
$.each(data,
function (i, item) {
$('#patientName').html(item.PatientName);
html += "<div class='col-md-3'> <div class='card'><div class='card_header'><h5>" +
item.DrugName +
"</h5></div><div class='card_body'>" +
"<div class='col-md-12'></div><ul class='col-md-6'><li class='bold'>Ref #</li><li class='bold'>" +
item.ReferenceNo +
"</li>" +
"</ul><ul class='col-md-6'><li class='center'>Refills</li><li class='fill'>1</li></ul>" +
"<table class='table table-bordered table-inverse'><tbody><tr><th>Prescriber</th><td>" +
item.PatientName +
"</td>" +
"</tr><tr><th>Last filled</th><td>Nov 14 2014</td></tr><tr><th>Next fill</th><td>Oct 16 2016</td></tr>" +
"<tr><th>Qty</th><td>" +
item.LastRefillQty +
"</td></tr><tr><th>Last Filled Dispensory</th><td>" +
item.LastRefillDispensory +
"</td></tr></tbody></table><form action='' class='cta center bold'>" +
"<label><input name='refill' type='checkbox' value='refill'>Refill</label></form></div></div></div>";
});
$('#refillcards').html(html);
}
Now I want to check how many check boxes are checked when click a button. How can I do this?
I know only answer in pure Javascript:
First, put this declaration at the top:
checkboxes = []; // No `var', it's global
This will initialize the stuff
function
init (n)
{
// n is the number of check boxes
checkboxes[0] = document.getElementById ('some-id');
checkboxes[1] = document.getElementById ('other-id');
// ...
checkboxes[n - 1] = document.getElementById ('different-id');
}
To check selection for a particular check box, do:
function
checkSelect (n)
{
if (n >= checkboxes.length)
{
throw "Index out of bounds: " + n;
}
return checkboxes[n].value;
}
Then, count all of then
function
count ()
{
var ret = 0;
for (var n = 0; n < checkboxes.length; n++)
{
if (checkSelect (n))
{
ret = ret + 1;
}
}
return ret;
}
var n = $( "input:checked" ).length;
you can replace input with a better selector if you want.

Get text and id from an li element on click with pure JS

I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.

Function mouseup in forEach at each loop

I have foreach loop:
objects.forEach(function(object) {
var button = '<tr><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$(button).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
but this can't work. I have one object listed only in each forEach cycle.
How can I correctly write onclick event for each point of loop.
You can append each item into your div inside the forEach loop:
objects.forEach(function(object) {
var button = $('<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + '</td></tr>');
button.mouseup(function(e) { if(e.which === 1) { runObject(object); } });
$(mydiv).append(button);
});
Try this
objects.forEach(function(object) {
var button = '<tr class="test_' + object.object.code + "'><td>' + object.object.code + '</td><td>' +
formatDistance(1456000) + '</td></tr>';
$('.test_' + object.object.code).mouseup(function(event) {
if (event.which == 1) {
runObject(object);
}
});
result += button;
});
$(mydiv).html(result);
you have to resolve syntax error
Here is one of the ways:
//Create an empty container
var $result = $();
[1,2,3,4].forEach(function(object) {
//Create TRs as jQuery objects (as opposed to strings), append whatever
var $button = $('<tr/>').append('<td>[' + object + ']: </td><td>' + ("this is " + object) + '</td>');
//Bing events, mouseup, click or whatever
$button.on("mouseup", function(e) {
//Add whatever conditions you like
if (e.which === 1) {
alert (object);
}
});
//Keep adding the TR to the container
$result = $result.add($button)
});
//Append all at once, outside the loop
$("#mydiv").empty().append($result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv"></div>

How make sticky headers for several table headers?

So I have a several tables with several rows and columns. Since the information is huge I want to keep the table headers fixed on top when scrolling.
When the one header comes, the previous one will hide and the current one will stay fixed.
This is the js code I have so far:
function makeTableHeadersSticky(tableId) {
var thArr = $(tableId + " th");
var thWidthsArr = [];
var calcWidth = 0;
$(tableId + " th").each(function(){
calcWidth = $(this).css("width");
thWidthsArr.push(calcWidth);
});
var pos = $(tableId).offset();
var thTop = pos.top + "px";
var count = 0;
$(tableId + " tr:first-child > th").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
count = 0;
$(tableId + " tr:last-child > td").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
$(window).scroll(function() {
//var firstRow = $(tableId + " tr:first-child").offset();
var lastRow = $(tableId + " tr:last-child").offset();
var w = $(window);
//console.log("(first,last): ("+(firstRow.top-w.scrollTop())+","+(lastRow.top-w.scrollTop())+")");
if(($(window).scrollTop() > pos.top) && (lastRow.top-w.scrollTop() >= 0)) {
$(tableId + " tr:first-child").css("position", "fixed");
$(tableId + " tr:first-child").css("top", "0px");
$(tableId + " tr:first-child").css("left", "9px");
} else {
$(tableId + " tr:first-child").css("position", "static");
$(tableId + " tr:first-child").css("top", thTop);
}
});
}
makeTableHeadersSticky("#myTable");
If you see on my code I played with the positions of the table and the last row of the table to see where the table is. This way I can set the header position as fixed or static.
Here is my jsfiddle
Everything works just fine here. You just omitted to call the makeTableHeadersSticky function for the second table :
makeTableHeadersSticky("#myTable2");
demo

Increase jquery variable by 1 on scroll

I'm having issues increasing a variable by 1 every time I scroll. I successfully increase the variable by 1, but only once. This is the code I got. I need to increase the variable page.
$(document).ready(function () {
$(document).scroll(function (e) {
currentPage = 0;
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
$.getJSON("../campus/Settings/TranslationSettings.ashx?command=show&page=" + currentPage + "&Lang=en", function (data) {
var items = [];
$.each(data.Keys, function (key, val) {
$("<ul/>", {
"class": "translateinfo",
html: "<li class='keystring'><span class='label'>text string:</span>" + val["text string"] + "</li>" + "<li class='autotranslate'><span class='label'>Automated translation:</span>" + val["automated translation"] + "</li>" + "<li class='functionnumber'><span class='label'>Function Number:</span>" + val["function number"] + "</li>" + "<li class='translateurl'><span class='label'>URL:</span>" + val["url"] + "</li>"
}).appendTo("#updatepanel");
});
});
}
});
});
Not sure if you copy/paste your entire code. But you're recreating currentPage everytime the user scroll
Working fiddle, I create the variable before the scroll loop.
var currentPage = 0;
$(document).scroll(function (e) {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
console.log(currentPage);
}
})
http://jsfiddle.net/dCr3Z/

Categories

Resources