JavaScript

122K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.

Share tech news, updates, or what's on your mind.

Sign up to Post

Can anyone please suggest how to covert  ticks to DateTime in JavaScript or Jquery. For example below is the format
i am getting ticks

636891926215555850

Thanks.
0
Microsoft Azure 2017
LVL 13
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Here's my code:

let cart = {products: [], totalPrice: 0}

Open in new window


If I were explaining this to someone, I would say that "cart" is an object with two properties: an empty array called "products" and a "totalPrice" property with a value of 0.

Is that correct?
0
I am trying to get the scale on chartjs to render but it is using he default:


	var chart = new CanvasJS.Chart("chartContainer", {
		display: true,
		title:{
			fontFamily: "'-apple-system','BlinkMacSystemFont','Segoe UI','Roboto','Helvetica Neue','Arial','Noto Sans','sans-serif','Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol','Noto Color Emoji'",
			text: "Last 10 Scores"              
		},
		options:{
			scales: {
				yAxes: [{
	                ticks: {
	                	min:0,
	                	max:21,
	                	stepSize:1,
	                }
            	}]
			}	
		},
		data: [{
			type: "line",
			dataPoints: [
				{ label: "04/13/2019",  y: 15  },
				{ label: "04/14/2019",  y: 14  },
				{ label: "04/15/2019",  y: 13  },
				{ label: "04/16/2019",  y: 12  },
				{ label: "04/17/2019",  y: 11  },
				{ label: "04/18/2019",  y: 10  },
				{ label: "04/19/2019",  y: 9  },
		
		}]
	});

Open in new window


the chart renders properly except for the scale, which should be 0 to 21 but shows default 0,10,20,30


TIA
0
Hi,

This following function works fine.

function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open('get', 'data.txt', true);
  xhr.onload = function () {
    console.log('ReadyState', this.readyState);
    console.log(this.status);
    if (this.status == 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window


However, when I use an arrow function for xhr.onload, the code is not working.
any idea why?  Also how should I fix this issue?

function loadData() {
  const xhr = new XMLHttpRequest();
  xhr.open('get', 'data.txt', true);

  xhr.onload = () => {
    console.log('ReadyState', this.readyState);
    console.log(this.status);
    if (this.status == 200) {
      document.getElementById('output').innerHTML = `<h1>${this.responseText}</h1>`;
    }
  }
  xhr.send();
}

Open in new window

0
Dear Experts,
I need to count down for 5 minutes from the page opened.

I found this javascript on the w3school and it works fine,

however I tried to modify it, but it didn't work.

All I want is to count down for 5 minutes,
how can I do that?
my code is below.
thank you


<script>

var now = new Date().getTime();

var MS_PER_MINUTE = 60000;

var myStartDate = new Date(now - (5 * MS_PER_MINUTE));

// Set the date we're counting down to
var countDownDate = myStartDate;

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  //var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  //var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
</script>

Open in new window

0
So I am modifying a copyright free script from online to work in my classroom. I am trying to get sound to play when I press the 'go' button but don't know exactly where the code should go. When you open up the "Double Click Me.html" file you will see the script to play the sound. I have the call to the playsound function in the  go() function. But for some reason no sound in playing. I've attached the file and all relevant code.

Look for some guidance where the call should go so I can play the sound file located in the 'sound' folder. Thanks!
0
i use the javascript code below. but I want to have comma and dollar sign like e.g. $3,079,095.75
do you know how to code it?

parseFloat(Math.round(data[index].totaldueamount * 100) / 100).toFixed(2)
0
Hi Team,

I am using the Datatable jquery plugin to sort the table which sorts well but when I compared the output of the same input with the c# code I found it is different. I have no idea why is it so and which sort is right. Enclosing runable code for c# with output, and the output of the DataTable js plugin sort.

looking forward to hearing from you.


using System;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		List<string> colors = new List<string>
        {
           
"VW Transporter (AMB Equipement)",
"VW Transporter - OBD (AMB EQUIPEMENT)",
"Vauxhall Insignia - Unit 390622",
"Vauxhall Insignia (TCSV11 Rev G – battery mounted)"

        };
        // Call Array.Sort method.
        List<String> displayNamesSorted = new List<string>(colors);
                        displayNamesSorted.Sort();
                        displayNamesSorted.Reverse();
                        
		
		foreach (string color in displayNamesSorted)
        {
            Console.WriteLine(color);
        }
	}
}

Output:
[i]VW Transporter (AMB Equipement)
VW Transporter - OBD (AMB EQUIPEMENT)
Vauxhall Insignia (TCSV11 Rev G – battery mounted)
Vauxhall Insignia - Unit 390622[/i]

[b][u]whereas when I sort using DataTable.js plugin of Jquery it comes out:[/u][/b]

[i]VW Transporter - OBD (AMB EQUIPEMENT)
VW Transporter (AMB Equipement)
Vauxhall Insignia - Unit 390622
Vauxhall Insignia (TCSV11 Rev G – battery mounted)[/i]

Open in new window

0
Hi Experts,

I am working on an application with Django on the backend and reactjs on the front end.  

The problem I have is whenever I refresh the page a slash is added to the end of the query string.

see for eg,

http://ntdldev.librariesnt.net/uuid/ts5806306a-949e-4a93-8aa6-d7e2c9909a68_2/

when I fetch the page for the first time it is

http://ntdldev.librariesnt.net/uuid/ts5806306a-949e-4a93-8aa6-d7e2c9909a68_2

without a slash at the end, hence it processes the query string and fetches the page I request. whereas when I refresh, it not going through the source, it bypasses debugging it adds a slash at end and the page fails for that query string.

Please help me in resolving this issue.

Any help is highly appreciated.
Thanks
0
Hi, I have the float array which is populated in c#

temperatureData= new float[570, 429];

Open in new window



I then prepare the data in c# to be send to the front end by doing the following (this might be where its going wrong)

System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer();
jSearializer.MaxJsonLength = int.MaxValue;
pd.TemperatureDataArray = jSearializer.Serialize(temperatureData);

ViewBag.TempDataArray = pd.TemperatureDataArray;

Open in new window



then in the front end i have

var tempDataArray = @(ViewBag.TempDataArray);


var imageTemperatureDataArray = JSON.stringify(tempDataArray);
imageTemperatureDataArray = JSON.parse(imageTemperatureDataArray);


alert(imageTemperatureDataArray[321, 228]);

Open in new window


However the value in position 321,228 in JS is not the same as in C#, so i assume its re-ordered the data some how


Can anyone advise where its getting muddled up?


I've attached the dataset which is was taken on a BP on this line
ViewBag.TempDataArray = pd.TemperatureDataArray


The correct value in the float array at this position  [321, 228] should be 346.795624
However in the front end i'm seeing 304.92453
0
Ensure Business Longevity with As-A-Service
Ensure Business Longevity with As-A-Service

Using the as-a-service approach for your business model allows you to grow your revenue stream with new practice areas, without forcing you to part ways with existing clients just because they don’t fit the mold of your new service offerings.

I have a javascript that collects and manipulates the url.
It works well, but on occasion it gathers parameters that I want to drop off.
Ideally, I just want three characters after the decimal point.
Here is an example of a bad result:
          LoanerPolicyUpdateMgr.asp%3FvarID%3D1272
I want it to be
          LoanerPolicyUpdateMgr.asp
Here is my script:
function GetURL(){
            var AppURL = "";
    if (window.location.href.indexOf('=') > -1) {
              AppURL = window.location.href.split('?')[1];
        }
          AppURL = AppURL.replace(/accessdenied=/gi, "");
          AppURL = AppURL.replace(/%2F/gi, "");
          AppURL = AppURL.replace(/%2E/gi, "");
          AppURL = AppURL.replace(/webapps20/gi, "");
          AppURL = AppURL.replace(/asp/gi, ".asp");
            
            var str =AppURL;
              var res = str.substring(0, 50);
             document.getElementById("AccessCode_AppURL").value = res;            
}
0
Here's my function:

exports.getProducts = (req, res, next) => {
  Product.fetchAll(products => {
    res.render("shop/product-list", {
      prods: products,
      pageTitle: "All Products",
      path: "/products"
    });
  });
};

Open in new window


fetchAll looks like this:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window


...and getProductsFromFile looks like this:

const getProductsFromFile = cb => {
  fs.readFile(p, (err, fileContent) => {
    if (err) {
      return cb([]);
    }
    cb(JSON.parse(fileContent));
  });
};

Open in new window


Tell me, please, if I'm explaining this correctly. I'm attempting to understand this stuff to the degree when I can explain it to others and I'm having a hard time.

What I've been taught / told is that I'm looking at an expression that's being passed as an argument to another function. That's the quintessential advantage / utility of a callback.

So, this:

products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}

Open in new window


...is being passed as an argument to:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window


BTW: An expression represents the "guts" of a function, correct?

Thing is, if I try to envision that based on face value, I see something like this:

static fetchAll(products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}) {
    getProductsFromFile(products => {
    res.render("shop/product-list", {
    prods: products,
    pageTitle: "All Products",
     path: "/products"
     });
}

Open in new window


That seems both convoluted and bogus.

I'm thinking that for all intents and purposes, the "getProductsFromFile" method would be written like this:

getProductsFromFile(products)

Open in new window


Instead of:

products => {
    res.render("shop/product-list", {
    prods: products,
    pageTitle: "All Products",
     path: "/products"
     });
}

Open in new window



All the examples I've seen have very basic functions being used to illustrate what a callback is. This is far more complex and, as a result, seems a little more complicated.

What I'm "smelling" is that when you pass this:

products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}

Open in new window


...as an argument into:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window

0
Hi
i) Many of you know that I am working on getting my phone game IDE setup working. I have my first potentially very good ideas to play with/test.
I received excellent advice to make the game in Java first to know exactly what I'm trying to do, so I'm ready. It's working in a Javax JFrame. (thanks a lot - got my mind right)
I have been studying Javascript, some iOS, a look at some c# pages, Xcode pages..

ii) I am not getting it done as quickly as I hoped..I have so many questions every minute, u know how it goes..
Do you think it could be a plan to ask a Freelancer to completely help set me up, maybe over the phone? Ability to make games on any, every device, browser? I prefer back and forth banter, not sporadic articles. too much waiting. I need some first downs.
How many languages, SDK's and devices are there to accommodate me in this situation, have to learn? What did the agar.io or slither.io dudes do? Javascript!? How did they cover everything, all devices!? iPhones need special features. What else?  J2ME is a bust, so I need a new angle. The agar.io dudes made an iPhone app! Also Android App? Windows phone?

iii) I have access to one of Godaddy's private professional servers. - got major repeat customer credits for an appealing price for 10 years in. I hope it will serve the potential max players well. non VPN (can be clogged) Can I expect this to serve my players as well as agar.io and slither.io  do?

Freelancer a plan?
Thanks
0
Hi

I read that J2ME can do Java code for phone apps and other thingies, like PDA's.
This is very good news. Is it as good, speed, efficiency as desktop?
But, it also can't use Eclipse Juno. - must be Indigo - is that a step backwards?
That is annoying. Must I really uninstall Juno to get Indigo up on MacBook? Does that mean just simply deleting the .app file in my applications folder? and then installing Indigo?
I'll lose all my project settings?

Thanks
0
Hi

I'd like to get my first Javascript test game onto my phone.

Do they expect .js files or HTML5?

How do I upload it - comple it to an app? Will it work on all devices? How do I accommodate different pixel dimensions in my code? - for identical gameplay on all devices, is there a stretch / affine transform?
Thanks
0
I'm a non-programmer (i.e., designer) using JQuery Mobile 1.2.1 (I know this is old, in the process of updating). When a visitor arrives at a particular static page via an outside link that includes a #hash at the end of the URL (i.e., "my-site.com/mypage.html#target", #target being a section inside a collapsible), I need a collapsible on that page to expand, then I need the page to scroll smoothly to the target of the hash.

At the moment, this is a very specific use case, where I know the exact section and the target I want to scroll to, but it would be nice if this code could be reusable for any external link coming to a page where I would like to scroll to any target that's inside any collapsible. At this point, I'd settle for anything that works, as this is a somewhat urgent request.

I'm able to accomplish this sort of thing when just navigating to targets within a page via click, but when arriving from outside the page/site via a hash link URL, the results are very random and somewhat unpredictable. The collapsible opens, and then either the page scrolls to the target then immediately resets to view to the top of the page, or the scroll lands off target by varying margins. Kinda maddening.

This is where I've arrived most recently before throwing up my hands and running here.

$(window).bind("load", function() {
    	var hashName = window.location.hash;
//because I know the specific hash, I put it in an if statement to keep it from possibly interfering 

Open in new window

0
I have this HTML:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script>
		function ls250_window() {
			window.open("show_summ_ls250.php");
			window.location = "my_projects.php";
		}	
	</script>
  </head>
  <body onLoad="ls250_window();">
  </body>
</html>

Open in new window


My intention is to open the window as indicated, then make the active window show my_projects.php. That part works.

The window.open does not. Is that because an absolute url is required? Like http://www.xyz.com/ (etc).

Or maybe a timer to make sure the window.open completes BEFORE the redirect?

Thanks
0
Hi
I think for my io game in javascript, it would help my game object layout if I knew if the game was being played on a phone or desktop.
What is the best way to do this?
Also. . . Clear the canvas for a game loop efficiently? Is Javascript rendering super-fast?
...and then place my game objects appropriately?

Thanks
0
Hi
If I am going to focus on phone / io games, I'd like to know about security issues like hacking, which is unavoidable w online games. I created a successful Authoritative Java RTS server. It could not be hacked. Slither.io has all game data local..  Are people messing around with slither, etc?

Surely, if they start my game from an io site - or on my business hosting private server, it is my official client code. - it is not their hack. Now they can hack my game variables, but can they simply make a map hack? Must I still have an authoritative server? I read that some games are just clients - update each other on all activity, no in-game server, just clients.

Is hacking something I ned to be vigilant about, yet?

Will it ever be?
Thanks
0
HTML5 and CSS3 Fundamentals
LVL 13
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Hi
For a phone io game,
I'd like to be able to click/touch one part of a line, and move it.
If the HTML sends in the size of the game-window, does a phone luncher pass in its size?  obviously. Is there a minimum size?
Thanks.
Are touches simply like mouse clicks? No special module?
0
I am attempting to use ngCookies to get user cookies data.
I am getting an error  which states:

uncaught TypeError: Cannot read property 'module' of undefined
    at angular-cookies.js:19
    at angular-cookies.js:253


angular.module('ngCookies', ['ng']).  // This is line in error twice

What am I missing.

Isaac

(function () {
    var app = angular.module('associatesProfileApp', ['ngCookies']);
    app.controller("associatesprofileController", function ($scope, $cookies) {

function SetCookiesForDebugging() {
            alert("in SetCookies");
            var thecookie;
            var thecookie = "departid=351&jobtitle=Digital+Developer+Sr&floor=0&username=ij25405&ps%5Fdeptname=Digital+Experience&ps%5Fdeptid=351&cost%5Fcenter=351&birthday%5Fday=16&birthday%5Fmonth=7&fsla=Exempt&psdeptname=Digital+Experience&managerwholename=Lawrence+Raffel&area=215&mailstop=%2D+None+Selected+%2D&managerid=21286&departmentid=0&extension=4844971263&emplid=ij25405&managerusername=LR22638&deptname=KY+Exec+Dir&cubeoffice%5Fno=+&ismanager=0&email=tmruk%40amerihealthcaritas%2Ecom&lob=1&fname=Isaac&is%5Fuserlive=1&psdeptid=351&url=%23&costcenter=351&lname=Johnson&company=KEY&managerphone=2159378142&is%5Fmanager=0&wholename=Isaac+Johnson&id=13332&building=0&guest="
            document.cookie = thecookie
        }

        function SetUser(getCookie) {
            alert("in getCookie")
            var manager = getCookie("ismanager");
            $scope.IsManager = (manager 

Open in new window

0
<p>	bullet point bug test</p><ul><li>	</li><li>		1	</li><li>		2	</li><li>		3	</li><li>		4	</li><li>		5</li></ul>

Open in new window



so i have a string from CKEDTIOR ,

it keeps adding in blank bullet points,

is their a way to remove the <li> </li> if it has no value inside it ?

for example keep the li with 1 , 2 ,3 but remove the first one which is blank ?
0
 <script type="text/javascript">
                function addNumbers()
                {
                        var val1 = parseInt(document.getElementById("timepicker").value);
                        var val2 = parseInt(document.getElementById("timepicker2").value);
                        var ansD = document.getElementById("answer");
                        ansD.value = val2 - val1;
                }
        </script>

<input type="button" name="Sumbit" value="Click here to calculate Time Spent" onclick="javascript:addNumbers()"/>
        Answer = <input type="text" id="answer" name="answer" value=""/>

Open in new window


The above code works for me when I use integers but how do I set it to be able to use decimal numbers as inputs from the textboxes and give the result as decimal
1
Hi

What do you think of me having in my game, a character with a sword, in a black cloth suit, just like Anakin on Mustafar, but he is called Pepe the Swindler? with a colorful sword?
How could Disney / LFilm kill me? I know them, they'd murder me. You can not copyright a story. How about a giant droid thing slightly similar to  general grievous? if I called him unpleasant robot.
There is fair use for situations like this, but does Disney / LF care?

Thanks
0
Hello, All.
(For reference, I will be using ASP Classic in this project, however. That should not matter on how you submit the form to the data side.)

OK.
I am using HTML5 Video on my site.
I would like to capture the time the video stops at, and save it to my database.
(The database work I have completed)
What I need to know, is how to save the form, when the video is stopped?

here is a link to the video test page.
https://www.cffcs.com/stuff/VideoTest.asp

Here are the video and form code.
<video width="100%" height="100%" autobuffer controls id="myvideo" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
<form name="displayurl" action="data/NewInsert.asp" method="post" onsubmit="xmlhttpPost('data/NewInsert.asp', 'displayurl', 'MotionDiv', '<img src=\'graph/pleasewait.gif\'>'); return false;">
        <input name="offseturl" type="text" readonly="" value="" size="50" onclick="document.displayurl.offseturl.focus();document.displayurl.offseturl.select();"/>
        <input type="hidden" name="Submit" value="Send Video Time" />
        <input type="hidden" name="UID" value="2" />
        <input type="hidden" name="MediaID" value="1" />
      </form>
      <div id="MotionDiv"></div>

Open in new window


On this page, you can view the source.
I added a hidden button to get me a "Name" and "value" to call in the code for inserting the data into the database.

Any assistance on this would be great.
Thanks.
Wayne
0

JavaScript

122K

Solutions

42K

Contributors

JavaScript is a dynamic, object-based language commonly used for client-side scripting in web browsers. Recently, server side JavaScript frameworks have also emerged. JavaScript runs on nearly every operating system and  in almost every mainstream web browser.