Home > Net >  Calling multiple functions to one value in javascript
Calling multiple functions to one value in javascript

Time:06-07

Probably an beginner question. When a counter I have on my page hits 10000 I am looking to reset the number to 1 and show " 10k" next to it.

For example, if the counter response was 10010 it would display as follows: Image of UI

I have created 2 functions that do both of these but I am not sure how to apply them both to the counter "WebsiteVisits", as currently the second one overwrites the first one. Here is the code:

// below changes 10000 to 1

function kFormatter(num) {
    if (num > 1 && num < 10000) {
    return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)): Math.sign(num)*Math.abs(num)
    
}
    else if (num > 10000 && num < 20000) {
      return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-500).toFixed(1)): Math.sign(num)*Math.abs(num)
}
}

// Below script shows  10k copy

function show10k(num) {
    if (num > 1 && num < 10000) {
            document.getElementById("10k-text").style.display = "none";
    
}
    else if (num > 10000 && num < 20000) {
            document.getElementById("10k-text").style.display = "flex";
}
}

// output

function websiteVisits(response) {
        document.querySelector("#visits").textContent = (kFormatter, show10k)(response.value);
}

CodePudding user response:

  1. first : function kFormatter(num) of you is wrong : (Math.abs(num)-500) should change to (Math.abs(num)-10000)
  2. (kFormatter, show10k) is returned show10k (document):
  • (kFormatter, show10k)(response.value) <=> show10k(response.value)
  1. You can call 2 function same as :
document.querySelector("#visits").textContent = kFormatter(response.value);
show10k(response.value)

or call show10k() in kFormatter() same as :

function kFormatter(num) {
  if (num > 1 && num < 10000) {
    show10k("none")
    return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-0).toFixed(1)): 
    Math.sign(num)*Math.abs(num)
  } else if (num > 10000 && num < 20000) {
    show10k("flex")
    return Math.abs(num) ? Math.sign(num)*((Math.abs(num)-10000).toFixed(1)): 
    Math.sign(num)*Math.abs(num)
  }
}

// Below script shows  10k copy

function show10k(display) {
   document.getElementById("10k-text").style.display = display;
}

CodePudding user response:

I'm not sure of the constraints of your project but this is how I would achieve the same thing:

if (input.value > 10000) {

    let tenKays = Math.floor(input.value / 10000)

    let digits = input.value % 10000

    output.innerHTML = digits   " "   " "   tenKays   "0K"

} else {

    output.innerHTML = input.value

}

It could be polished in different ways to display the actual output in a more sophisticated way but it's a simple method that handles numbers of any size.

  • Related