How to call a function more then once? - javascript

How would I go about calling a function multiple times in different parts of my code. Currently I am just replicating the function and giving all of the variables a different name and calling that separate variable. I will add an example below. The method works but there is no way its efficient. What would be the better way to do it? Thank you for the help and I apologize for the silly question.
JS
// Variable 1
const filterButtons = document.querySelector("#filter-btns").children;
const items = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons.length; i++) {
filterButtons[i].addEventListener("click", function(){
for (let j =0; j < filterButtons.length; j++) {
filterButtons[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items.length; k++) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
})
}
// Variable 2
const filterButtons2 = document.querySelector("#filter-btns2").children;
const items2 = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons2.length; i++) {
filterButtons2[i].addEventListener("click", function(){
for (let j =0; j < filterButtons2.length; j++) {
filterButtons2[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items2.length; k++) {
items2[k].style.display = "none";
if (target == items2[k].getAttribute("data-id")) {
items2[k].style.display = "block";
}
if (target == "all") {
items2[k].style.display = "block";
}
}
})
}
HTML
<div id="filter-btns">
<a data-target="corn">
<span>Corn</span>
</a>
</div>
<div id="filter-btns2">
<a data-target="chicken">
<span>Chicken</span>
</a>
</div>

First, you need a function to call if you want to call it twice
function fn(query) {
const filterButtons = document.querySelector(query).children;
const items = document.querySelector(".blog__content").children;
for (let i = 0; i < filterButtons.length; i++) {
filterButtons[i].addEventListener("click", function () {
for (let j = 0; j < filterButtons.length; j++) {
filterButtons[j].classList.remove("active2");
}
this.classList.add("active2");
const target = this.getAttribute("data-target");
for (let k = 0; k < items.length; k++) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
});
}
}
Then you can call it twice
fn('#filter-btns');
fn('#filter-btns2');

Related

Variable is already defined with local variables? How?

This is my code for checking a register page. It says that variables i and j are already defined, although it's local variables and not global. What could I do in this situation? How can I make the vars locally and not globally? Help is really appreciated, I am a new student in Computer Science.
function checkName() { // בודק על
var n = document.getElementById("FullName").value;
var len = n.length;
var no = "!##$%^&*()-_+=\'|][}{><./,;:?,";
var num = "0123456789";
if (n == "") {
document.getElementById("errName").innerHTML = "רשום את השם בבקשה";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
if (len < 2) {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אות אחת";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) >= "a" && n.charAt(i) <= "z") {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אותיות באנגלית";
return false;
}
}
for (var i = 0; i < no.length; i++) {
for (var j = 0; j < n.length; j++) {
if (no.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור תווים מיוחדים";
return false;
}
}
}
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
for (var i = 0; i < 3; i++) {
if (n[i] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
if (n[i + 1] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
}
}
}
document.getElementById("errName").innerHTML = "";
return true;
}
Javascript has function scope, so defining any variable in a function with var will make it exist throughout the function.
In each for loop, you redefine i with var i = 0. For example:
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
...
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
You can add a var i; at the top of the function instead, and simply say i=0 in your loops, so you don't define it multiple times.
Consider looking into using let in newer JS versions.
Try to use new ES6 let instead of var to declare a variables in your functions/project.
This will solve your issue with global name scope.
You can read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You need to look into function scoping. As var has scope of function in which it is defined.
So in your case variable i has access inside checkName function. Using let will help you out in above scenario.

What does var this.mtx[i][lead] do in javascript?

I was going through a reduced row echelon form code for javascript from this website: http://rosettacode.org/wiki/Reduced_row_echelon_form#JavaScript and I was trying to put it into simpler code so that I could understand what each instruction did. I then ran into: while (this.mtx[i][lead] == 0). I understand what the this.mtx[i] is but I don't know what [lead] in the context of being right after mtx[i] does. Your helps is greatly appreciated. Here is the code:
Matrix.prototype.toReducedRowEchelonForm = function() {
var lead = 0;
for (var r = 0; r < this.rows(); r++) {
if (this.columns() <= lead) {
return;
}
var i = r;
while (this.mtx[i][lead] == 0) {
i++;
if (this.rows() == i) {
i = r;
lead++;
if (this.columns() == lead) {
return;
}
}
}
var tmp = this.mtx[i];
this.mtx[i] = this.mtx[r];
this.mtx[r] = tmp;
var val = this.mtx[r][lead];
for (var j = 0; j < this.columns(); j++) {
this.mtx[r][j] /= val;
}
for (var i = 0; i < this.rows(); i++) {
if (i == r) continue;
val = this.mtx[i][lead];
for (var j = 0; j < this.columns(); j++) {
this.mtx[i][j] -= val * this.mtx[r][j];
}
}
lead++;
}
return this;
}

How to reduce time of execution for javascript code

Below is my code which is taking time in the for loop to extract data from one object and filling another object. Is there any way to reduce the time of execution? I have tried a while loop but it is not helping that much. Kindly help
function SetGridWithData(result) {
if (!result) {
return;
}
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (result.length >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
} else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
} else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < result.length; i++) {
boxOfJson.push(result[i]);
}
}
}
I am trying to implement paging which is done, but 100 data per page first it will check page no 0 if it is then loop one and if other than 0 than else case.
You could try caching result.length at the beginning of your function (following the if check at the beginning)..
function SetGridWithData(result) {
if (!result) { return; }
var resultLength = result.length;
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (resultLength >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
}
else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
}
else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < resultLength; i++) {
boxOfJson.push(result[i]);
}
}
}

uncheck Function doesnt work

it seem i solve this question myself~
in a simple and stupid way :
Checkall Box
var tab = document.getElementById("tbl");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (tab.checked == elems.checked)
{
elems[i].checked = true;
}
}
UncheckAll Box :
for (var i = 0; i < len; i++) {
if (tab.checked == elems.checked)
{
elems[i].checked = false;
}
}
it seem i solve this question myself ~~
Checkall Box
var tab = document.getElementById("tbl");
var elems = tab.getElementsByTagName("input");
var len = elems.length;
for (var i = 0; i < len; i++) {
if (tab.checked == elems.checked)
{
elems[i].checked = true;
}
}
}
UncheckAll Box :
for (var i = 0; i < len; i++) {
if (tab.checked == elems.checked)
{
elems[i].checked = false;
}
}
}

can any one tell me whats the wrong with code

function MoveAddToCartAccordingly()
{
var elems = document.getElementsByClassName('box-collateral box-related');
var av = document.getElementsByClassName('availability in-stock');
var sp = document.getElementsByClassName('product-options');
var ac = document.getElementsByClassName('add-to-cart');
var first = document.getElementsByClassName('item first');
var second = document.getElementsByClassName('item');
for(var k = 0; k < sp.length; k++){
if (getComputedStyle(sp[k]).visibility == "visible")
{
for (var i = 0; i < elems.length; i++) {
if (getComputedStyle(elems[i]).visibility == 'visible') {
for (var j = 0; j < av.length; j++) {
av[j].style.visibility = 'visible';
av[j].id = "someID";
elems[i].appendChild(av[j]);
}
}
else
{
for (var s = 0; s < av.length; s++) {
av[s].style.visibility = 'hidden';
}
for (var l = 0; l < ac.length; l++) {
ac[l].style.marginTop = "-500px";
ac[l].style.marginLeft = "-20px";
}
}
}
}
return;
}
for (var p = 0; p < elems.length; p++) {
if (getComputedStyle(elems[p]).visibility == 'visible') {
for (var q = 0; q < av.length; q++) {
av[q].style.visibility = 'visible';
av[q].id = "someID";
elems[p].appendChild(av[q]);
}
if(elems[p].style.marginTop == "-610px")
{
elems[p].style.marginTop = "-640px";
}
for(var r = 0; r < first.length; r++)
{
if(getComputedStyle(first[r]).visiblity == 'visible'){
for(var m = 0; m < ac.length; m++)
{
if(ac[m].style.marginTop == "-120px")
{
ac[m].style.marginTop ="-140px";
}
}
}
else if(getComputedStyle(first[r]).visiblity == 'visible' && getComputedStyle(second[r]).visiblity == 'visible' )
{
for(var n = 0; n < ac.length; n++)
{
if(ac[n].style.marginTop == "-120px")
{
ac[n].style.marginTop ="-140px";
}
}
}
}
}
}
}
window.onload = MoveAddToCartAccordingly;
can any one whats the wrong with code here actually i am checking if div product option is visible then again i am checking if div with class "box-colatral box-related" if visible if it is not then i am hidding other tag p with class Availability-in-stock and moving add-to- cart div to top position but that one is not working
You have a return statement in your first for loop. I imagine that you are always going to bail on the function call after the first iteration of that loop.

Categories

Resources