Can't display this simple .hide() code in Internet explorer - javascript

I have been trying this piece of code on a page and it is working fine in Chrome as well as Firefox.
But not in Internet Explorer, only the alert function within the if condition will show up.
$('#element-14').change(
function(){
$('.late').hide();
$('.normal').hide();
var tempDate= new Date();
var dateViolatetmp = $('#element-14').val();
var dateViolatearr = dateViolatetmp.split('/');
var dateViolate= new Date(dateViolatearr[2],(parseInt(dateViolatearr[0],10)-1).toString(),dateViolatearr[1]);
var one_day=1000*60*60*24;
var tempDate_unixtime =tempDate.getTime() ;
var dateViolate_unixtime =dateViolate.getTime();
var dayDifference = Math.round((tempDate_unixtime/one_day)) - Math.round((dateViolate_unixtime/one_day));
if(dayDifference<=30){
$('.normal').show();
alert("ok1");
}
else{
$('.late').show();
alert("ok2");
}
});

Do you see all the values as expected in the console with this code? The reason I wrote if(console) conditions is because I'm not sure if it even exists in IE (otherwise would not surprise me a bit(!) and I don't have it installed).
$('#element-14').change(function() {
if (console) console.log('#element-14 changed.');
$('.late, .normal').hide();
var arr = $('#element-14').val().split('/');
if (console) {
console.log('val:',$('#element-14').val());
console.log('arr:',arr);
}
var dateV = new Date(parseInt(arr[2]), parseInt(arr[0])-1, arr[1]);
if (console) console.log('dateV:',dateV);
var one_day = 1000*60*60*24;
var now = new Date();
if (console) console.log('now:',now);
var dayDiff = Math.round((now.getTime()-dateV.getTime()) / one_day);
if (console) console.log('dayDiff:',dayDiff);
$(dayDiff <= 30 ? '.normal' : '.late').show();
});

Related

[indesign][js] dialog or palette - not show up

have problem with script.
need open a window with some information, which will automatically disappear after 3 seconds.
my code:
#targetengine "session"
var windowX = new Window("dialog"); // v2 palette
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
var image1_imgString = "%C2%89PNG%0D%0A%1A..."
var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
dialog show, palette not
if I add ...
var timerBreak = new Date().getTime() + 3000;
var now = new Date().getTime();
while(now<timerBreak){
now = new Date().getTime()
}
windowX.close();
nothing happend (happend: first: loop, next: window show and close at the same time) - why?
if i add ...
windowX.addEventListener('show',function(){
...
}
same ...
but if i add alert("dhgkjsd") ... for check ... dialog (or palette) show and wait for click on messagaebox
how to make a timer that will close the displayed window 3 seconds after opening?
Unfortunately, I do not have a copy of InDesign to test this, but the code below works in AfterEffects.
#targetengine "session"
// To be called later
function closeMe() {
windowX.close();
}
// Timer as a variable
var delay = 3000;
// a pallette, and not a modal, like in your
// original code, because the modal is UI blocking
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
windowX.show();
// This is the key part
app.setTimeout(closeMe,delay);
app.setTimeout() has been suggested as a way of delaying code execution, which is what you need in this case (delaying of windowX.close()). Please note the author's comments (check the link) - app.setTimeout() has been made available from AE version CC 2015.
It can be done this way:
var windowX = new Window("palette");
windowX.orientation = "row";
windowX.preferredSize.width = 200;
windowX.preferredSize.height = 200;
windowX.alignChildren = ["center","center"];
windowX.spacing = 15;
windowX.margins = 16;
// var image1_imgString = "%C2%89PNG%0D%0A%1A..."
// var image1 = windowX.add("image", undefined, File.decode(image1_imgString), {name: "image1"});
windowX.show();
// here is the magic
windowX.update();
$.sleep(3000); // 3 seconds
windowX.hide();
windowX = null;
Based on the example from here: https://community.adobe.com/t5/illustrator-discussions/auto-close-alert-message/td-p/9398258
#Yuri ... windowX don't show before $.sleep (use instead var timerBreak...) - but only my Mac. Another Mac - your code works.
I write something like this:
//create windowX
var oneIdleTask = app.idleTasks.add({
name: "one_idle_task",
sleep: 1
}); // sleep not working here - write 3000 and nothing change
var onIdleEventListener = oneIdleTask.addEventListener(IdleEvent.ON_IDLE,
function() {
var oneIdleTaskName = "one_idle_task";
var oneIdleTask = app.idleTasks.itemByName(oneIdleTaskName);
if (oneIdleTask != null) {
oneIdleTask.remove();
$.sleep(3000) //<- write sleep here ... but deley is ok (for me) without this
windowX.hide();
}
}
);
windowX.show();

WebCL doesn't fill global table

I started using Nokia WebCL implementation for Mozilla Firefox.
I'm testing my application on Firefox version 32.0 (which is version for which Nokia binding was implemented).
This is my code (for simplicity and to show you what my issue is I've simplified the kernel code to minimum):
Kernel code:
<script id="julia_set" type="text/x-opencl">
__kernel void julia_set(__global int* pix)
{
pix[0]=5;
}
</script>
My Javascript code:
function loadKernel(id){
var kernelElement = document.getElementById(id);
var kernelSource = kernelElement.text;
if (kernelElement.src != "") {
var mHttpReq = new XMLHttpRequest();
mHttpReq.open("GET", kernelElement.src, false);
mHttpReq.send(null);
kernelSource = mHttpReq.responseText;
}
return kernelSource;
}
var platforms = webcl.getPlatforms();
var width = 2;
var height = 2;
var ctx = webcl.createContext(platforms[2],WebCL.DEVICE_TYPE_GPU);
var length = 4*width*height;
var bufSize = 4*length;
var bufferC = ctx.createBuffer (WebCL.MEM_WRITE_ONLY, bufSize);
var kernelSrc = loadKernel("julia_set");
var program = ctx.createProgram(kernelSrc);
var device = ctx.getInfo(WebCL.CONTEXT_DEVICES)[0];
try {
program.build ([device], "");
} catch(e) {
alert ("Failed to build WebCL program. Error "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_STATUS)
+ ": "
+ program.getBuildInfo (device,
WebCL.PROGRAM_BUILD_LOG));
throw e;
}
var kernel = program.createKernel ("julia_set");
kernel.setArg (0, bufferC);
var cmdQueue = ctx.createCommandQueue (device);
var local = [16,16];
var global = [32,32];
cmdQueue.enqueueNDRangeKernel(kernel, 2, null,global, local);
var outBuffer = new Uint32Array(length);
cmdQueue.enqueueReadBuffer (bufferC, false, 0, bufSize, outBuffer);
cmdQueue.finish ();
console.log(outBuffer);
It's the most simple OpenCL application I could imagine. I expect my outBuffer to be filled with 0's and first element to be 5, but all the elements are 0. Whatever I try to do in kernel, my array seems untouched.
The device I'm using is NVidia GeForce GT 750M.
What can be possibly wrong in my code?
if(get_global_id(0)==0 && get_global_id(1)==0)
pix[0]=5;
should fix the issue, without race condition.

Why isn't this function reading and displaying cookie?

I have written this code. But it isn't displaying cookie. It displays only prompt again and again, whenever I open this page. How can I correct it?
<body onload="myFunc()">
<script>
function createCookie(value, exdays)
{
var date= new Date();
var d= date.setTime(date.getDate()+(exdays*10000));
var e = date.toUTCString(d);
var g = document.cookie= "user="+value+";"+" "+"expires="+e;
return g;
}
function readCookie()
{
var h = document.cookie;
var i= h.split(";");
return i[0];
}
function myFunc()
{
var a= readCookie();
if(a!="")
{
alert("Welcome"+a);
}
else
{
var b = prompt("Enter your name", "");
createCookie(b, 5);
}
}
Javascript IS case sensitive:
var date = new Date();
Your snipped works fine in most browsers, even in chrome. Except you are working on your local file-system (URL = file:///xxx). Chrome has local file cookies on default disabled but you can activate them with command-parameters '--allow-file-cookies'.

Play sound ONLY ONCE

I'm making a small asteroid avoiding game and when my lives are over I'm executing the following code:
gameover.play();
while gameover is defined like so:
var gameover = new Audio('gameover.wav');
When I execute the code, it loops the sound and I want to play it just once, how would I do that? Thanks.
I believe setting the loop property to false will accomplish your goal.
var birdSound = new Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
birdSound.play();
var birdSound = new Audio('http://www.noiseaddicts.com/samples_1w72b820/4929.mp3');
birdSound.loop = false;
birdSound.play();
var statusElem = document.getElementById('status');
var startTime = Date.now();
updateStatus();
function updateStatus(){
if (birdSound.ended){
statusElem.innerText = 'Stopped';
} else {
statusElem.innerText = 'Playing (' + ( ( Date.now() - startTime ) / 1000 ) + ')';
window.setTimeout(updateStatus, 50);
}
}
Audio Status: <span id="status">Playing</span>
Tested in:
Chrome 44.0.2403.155 (64-bit)
Firefox 40.0.2
Safari 8.0.6
Vivaldi 1.0.94.2 (for giggles)

getElementsByTagName().length doesn't work in Firefox / Internet Explorer

This is related to another question (Chart is rendered in Chrome, but not in FF and IE), however, I am of the opinion that it is a valid question in itself and this will hopefully help describing the problem more in-depth.
I realized this behavior when I opened my webpage with Firefox by chance and noticed that my amChart graph wasn't working anymore, which I traced back to these lines in the code:
xmlData = xmlHttp.responseXML;
var x=xmlData.getElementsByTagName("row");
xmlRowCount = x.length;
Apparently the Firefox & Internet Explorer engines execute "xmlData.getElementsByTagName" differently from Google Chrome (where it works fine), which in turn leads to wrong return values and therefore an utter breaking of all following code.
The question is why FF and IE do this and how to prevent them from doing it and return the proper result just like Chrome.
I appreciate any suggestions and hope that some of you can help me and might know the reason for this strange behavior.
best regards,
daZza
Edit: To make the browser test complete, I also downloaded and tested Opera. It works fine there, which makes this whole thing even stranger. What is the difference between IE/FF vs. Chrome/Opera?
EDIT2: This finding looks promising... I tried adding a second console.log message that prints out the same thing, but uses the "non namespace name" of the XML tag, in this case z:row instead of row (row is the namespace name, z:row is the hard tag in the xml file).
What I discovered is, that Firefox/IE return 417 with this new console.log on the non-namespace name. Chrome/Opera return 0. And the same is true vice-versa, so Chrome returns 417 using the namespace, while FF/IE return 0.
This leads me to believe, tha FF/IE have a broken XML DOM that cannot utilize/use/detect/... namespaces in XML files.
I guess the only fix in that case is to use a XML without a namespace so it works on all browsers?
Here's a short example of the XML file (taken from a Sharepoint API):
<xml xmlns:s='uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882'
xmlns:dt='uuid:C2F41010-65B3-11d1-A29F-00AA00C14882'
xmlns:rs='urn:schemas-microsoft-com:rowset'
xmlns:z='#RowsetSchema'>
<s:Schema id='RowsetSchema'>
<s:ElementType name='row' content='eltOnly' rs:CommandTimeout='30'>
<s:AttributeType name='blub' rs:name='blah' rs:number='1'>
<s:datatype dt:type='string' dt:maxLength='512' />
</s:AttributeType>
</s:ElementType>
</s:Schema>
<rs:data>
<z:row blub="blahblah" />
</rs:data>
</xml>
PS: Here's are some code snippets that might be relevant to the issue:
JS section at the bottom of the HTML header (this is where the error occurs):
var xmlRowCount;
var arrArt = new Array();
var arrPriority = new Array();
var arrTermin = new Array();
var arrResult = new Array();
var arrCalcPrio = new Array();
var avgCalcPrio = new Array();
var terminCounter = 0;
var avgCounter = 0;
// button_bereichand button_unterbereich are the values from two dropdown boxes. --> Shouldn't have relevance for the problem at hand. The xmlFile parameter is an well formed and validated XML file within the same domain.
function loadXML(xmlFile, button_bereich, button_unterbereich)
{
var xmlHttp = null;
var xmlData;
var sum = 0;
var bereich = button_bereich;
var unterbereich = button_unterbereich;
var spUnterbereich = "";
console.log("Bereich: " + bereich);
console.log("Unterbereich: " + unterbereich);
arrArt.length = 0;
arrPriority.length = 0;
arrCalcPrio.length = 0;
if (typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp)
{
try
{
xmlHttp = new ActiveXObject("Msxm12.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Mircosoft.XMLHTTP")
}
catch(e)
{
xmlHttp = null;
}
}
}
if (xmlHttp)
{
var url = xmlFile;
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4)
{
var txt="";
xmlData = xmlHttp.responseXML;
var x=xmlData.getElementsByTagName("row");
xmlRowCount = x.length;
// Chrome: 417 | Firefox: 0 | Internet Explorer: 0
console.log("Rowcount: " + xmlRowCount);
for (i=0;i<xmlRowCount;i++)
{
// do something with each row
}
for (j=0;j<xmlRowCount-1;)
{
// do something
}
}
}
}
xmlHttp.send();
}
return xmlData;
}
// bereichElement and bereichText are the values from two dropdown boxes. --> Shouldn't have relevance for the problem at hand
function getGraph()
{
chartData.length = 0;
validateData();
var bereichElement = document.getElementById("bereich");
var bereichText = bereichElement.options[bereichElement.selectedIndex].text;
var unterbereichElement = document.getElementById("unterbereich");
var unterbereichText = unterbereichElement.options[unterbereichElement.selectedIndex].text;
var xmlDoc=loadXML("sp_xml.xml", bereichText, unterbereichText);
}
JS in HTML Body( Body has body onload="getGraph();"> parameter):
// Actual chart creation (amCharts lib)
var chart;
var chartData = [];
var chartCursor;
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "amcharts/images/";
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.dataDateFormat = "YYYY-MM-DD";
chart.baseHref = true;
// listen for "dataUpdated" event (fired when chart is rendered) and call zoomChart method when it happens
chart.addListener("dataUpdated", zoomChart);
// AXES
// category
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true;
categoryAxis.minPeriod = "DD";
categoryAxis.dashLength = 1;
categoryAxis.gridAlpha = 0.15;
categoryAxis.minorGridEnabled = true;
categoryAxis.axisColor = "#DADADA";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0.2;
valueAxis.dashLength = 1;
chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.title = "red line";
graph.valueField = "visits";
graph.bullet = "round";
graph.bulletBorderColor = "#FFFFFF";
graph.bulletBorderThickness = 2;
graph.bulletBorderAlpha = 1;
graph.lineThickness = 2;
graph.lineColor = "#0db503";
graph.negativeLineColor = "#b5030d";
graph.balloonText = "[[category]]<br><b><span style='font-size:14px;'>value: [[value]]</span></b>";
graph.hideBulletsCount = 50;
chart.addGraph(graph);
// CURSOR
chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorPosition = "mouse";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chartScrollbar.graph = graph;
chartScrollbar.scrollbarHeight = 40;
chartScrollbar.color = "#FFFFFF";
chartScrollbar.autoGridCount = true;
chart.addChartScrollbar(chartScrollbar);
// WRITE
chart.write("charts_container");
});
// this method is called when chart is first inited as we listen for "dataUpdated" event
function zoomChart() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
chart.zoomToIndexes(chartData.length - 40, chartData.length - 1);
}
// changes cursor mode from pan to select
function setPanSelect() {
if (document.getElementById("rb1").checked) {
chartCursor.pan = false;
chartCursor.zoomable = true;
} else {
chartCursor.pan = true;
}
chart.validateNow();
}
function validateData()
{
chart.validateData();
console.log("Data validated");
}
Your issue is that getElementsByTagName as specified in http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-A6C9094 specified matching on the "tagname", not the local name, and the tag name includes the prefix (see http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-104682815 where it explicitly says the tagName is the qualified name).
That's the behavior Firefox and IE implement.
WebKit never implemented that spec correctly, matching only on localName instead, as far as I can tell.
You can work around that by using getElementsByTagNameNS, which lets you explicitly match on localname only in all modern browsers. You can either pass in your actual namespace, or just "*" if you don't care about the namespace part.

Categories