mardi 4 août 2015

How to write a good Caps Lock detection solution in JavaScript?

EDIT: Figured it out on my own

For whom it may concern, a solution for caps detection in vanilla JavaScript. The problem with most of the solutions floating around on the internet is they only show/hide an alert/popup when the user starts typing in the input field. This is not optimal because the "Caps Lock is on" notification is still visible after the user has turned Caps Lock off, and remains so until they resume typing. This is long and unwieldy, and I still don't quite understand it myself. But I recommend it all the same.

function capsDetect() {
  var body = document.getElementsByTagName('body')[0];
  var isShiftPressed = false;
  var isCapsOn = null;
  var capsWarning = document.getElementById('caps-lock-warning');
  body.addEventListener('keydown', function(e) {
  var keyCode = e.keyCode ? e.keyCode : e.which;
  if (keyCode = 16){
   isShiftPressed = true;
}
});
body.addEventListener('keyup', function(e) {
 var keyCode = e.keyCode ? e.keyCode : e.which;
 if(keyCode == 16) {
   isShiftPressed = false;
}
 if(keyCode == 20) {
  if(isCapsOn == true) {
   isCapsOn = false;
   capsWarning.style.visibility = 'hidden';
} else if (isCapsOn == false) {
  isCapsOn = true;
  capsWarning.style.visibility = 'visible';
}
}
});
body.addEventListener('keypress', function(e) {
  var keyCode = e.keyCode ? e.keyCode : e.which;
  if(keyCode >= 65 && keyCode <= 90 && !isShiftPressed) {
    isCapsOn = true;
    capsWarning.style.visibility = 'visible';
} else {
    capsWarning.style.visibility = 'hidden';
}
});
}
shiftCaps();



via Chebli Mohamed

Modifying values of existing layer in OpenLayers 3

I am adding a marker on the map using ol3 by calling the following function

function addmarker(lat, long, flag) {

            iconFeature = new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.transform([+long, +lat], 'EPSG:4326', 'EPSG:3857')),
                name: 'NULL'
            });

            iconStyle = new ol.style.Style({

                fill: new ol.style.Fill({
                    color: '#008000'
                }),
                stroke: new ol.style.Stroke({
                    color: '#008000',
                    width: 3
                }),
                image: new ol.style.Circle({
                    radius: 6,
                    fill: new ol.style.Fill({
                        color: '#008000'
                    })
                })

            });

            iconFeature.setStyle(iconStyle);

            vectorSource[flag] = new ol.source.Vector({
                features: [iconFeature]
            });

            vectorLayer[flag] = new ol.layer.Vector({
                source: vectorSource[flag]
            });

            map.addLayer(vectorLayer[flag]);

        }

And to change the marker position, I am removing the layer and adding a new layer again

 function changemarker(lat, long, flag) {

             vectorSource[flag].clear();

            map.removeLayer(vectorLayer[flag]);

            addmarker(lat, long, flag);

        }

I am facing performance issues as I am changing the marker that is calling the changemarker method every 500 milliseconds. Can a layer be modified without removing it or is there a better approach that can be followed.

Please help.



via Chebli Mohamed

How to pass unknown children of Polymer component into component's DOM

I want to create a component which I can pass other components to and create DOM structures.

<test-component>
    <img/>
    <div/>
    <foo/>
</test-component>

In trying to get that working:

<dom-module name="test-component">
    <template>
        <h1>Title</h1>
        <ul>
            <template is="dom-repeat" items="{{nodes}}">
                <li>element:</li>
                <li>{{item}}</li>
            </template>
        </ul>

        <content id="contentelement"></content>
    </template>
</dom-module>

<script type="text/javascript">
    Polymer({
        is: "test-component",
        ready: function() {
            this.nodes = (function(that) {
                var nodeList = that.$.contentelement._distributedNodes,
                    nodeMap = [];
                for(var i = 0; i < nodeList.length; i++) {
                    if(nodeList[i].nodeType === 1) {
                        nodeMap.push(nodeList[i].outerHTML);
                    }
                }
                return nodeMap
            }(this));
        }
    });
</script>

I used a function to build this.nodes because this.nodes = this.$.contentelement.getDistributedNodes(); returns null, not sure why.

I know you can't just drop an element's outerHTML into the page but can a random set of HTML/components be passed into a template like this?



via Chebli Mohamed

Javscript is not hiding div & input element

I've got a div & input that needs to be hidden on the page load. It is a other specify, so if one of the other fields is selected "other" then the div should show. But the input element is not hiding on page load. As soon as I take out the input element from the div it hides, but as soon as I put the input element back it does not hide, what am I doing wrong?

<head>
<script>
function hideother() {
    document.getElementById("otherdiv").style.visibility = "hidden";
    document.getElementById("others").style.visibility = "hidden";
}
</script>
</head>

<body onLoad="hideother()">
    <!-- 2A OTHER SPECIFY -->
    <div class="otherdiv">
    <label for="otherspecify">Please specify other:</label>
    <label id="error-2" style="text-transform:capitalize; color:red">&nbsp;</label>
    <br>
<input maxlength="30" name="others" id="others" type="text" class="form-control" placeholder="Other Specify" autocomplete="off" style="width:300px" />
    </div>
</body>



via Chebli Mohamed

AngularJS service parent separate reference

I'm using an AngularJS service to store data from multiple pages, to be submitted together. See the code below.

In my Chrome console if I observe checkoutData.shipping, I get back the correct object with data. If I observe checkoutData.data I get an empty object, where it's shipping property is blank.

These should be pointing at the same object, right? Why would it work with .shipping and not using .data? The reason it's set up this way is that the shipping page only cares about .shipping, while the final page needs everything in .data.

(function() {
    angular.module('app').factory('checkoutData', [function() {
        var data = {
            carrierId: null,
            serviceTypeId: null,
            shippingCost: {},
            billingOptionId: null,
            shipping: {},
            billing: {},
            cart: null
        };
        var inputForms = {};
        var options = {
            shippingOptions: null,
            billingOptions: null,
            selectedShippingOption: null
        };
        var staticContent = {
            billing: {},
            cart: {},
            shipping: {}
        };
        return {
            data: data,
            shipping: data.shipping,
            inputForms: inputForms,
            cart: data.cart,
            billingOptionId: data.billingOptionId,
            billingOptions: options.billingOptions,
            carrierId: data.carrierId,
            serviceTypeId: data.serviceTypeId,
            shippingOptions: options.shippingOptions,
            staticContentBilling: staticContent.billing,
            staticContentCart: staticContent.cart,
            staticContentShipping: staticContent.shipping,
            selectedShippingOption: options.selectedShippingOption,
            setValid: function(formName, valid) {
                inputForms[formName].valid = valid;
            },
            initializeForm: function(formName) {
                inputForms[formName] = {};
            },
            formInitialized: function (formName) {
                return inputForms[formName] != null;
            }
        }
    }]);
})();



via Chebli Mohamed

i have two fields.today sale and yesterday sale.i want to change the image when sale valuew change how can i change that?

I found this script: http://ift.tt/1gHeQZi Unfortunately I can't login. I had a look at the code but can't figure out what is wrong. When starting this script the user has to type ...



via Chebli Mohamed

XPathEvaluator in Firefox addon

I am attempting to follow this article to evaluate an XPath expression. My code is copy/pasted from the article:

// Evaluate an XPath expression aExpression against a given DOM node
// or Document object (aNode), returning the results as an array
// thanks wanderingstan at morethanwarm dot mail dot com for the
// initial work.
function evaluateXPath(aNode, aExpr) {
  var xpe = new XPathEvaluator();
  var nsResolver = xpe.createNSResolver(aNode.ownerDocument == null ?
    aNode.documentElement : aNode.ownerDocument.documentElement);
  var result = xpe.evaluate(aExpr, aNode, nsResolver, 0, null);
  var found = [];
  var res;
  while (res = result.iterateNext())
    found.push(res);
  return found;
}

However, I'm getting this error:

Message: ReferenceError: XPathEvaluator is not defined

Is Mozilla's article out of date, perhaps? Is there a more up-to-date article available on parsing XML in an SDK add-on?

Edit. When I tried it this way:

var {Cc, Ci} = require("chrome");
var domXPathEvaluator = Cc["@http://ift.tt/1II9uXP"].createInstance(Ci.nsIDOMXPathEvaluator);

I got a long error message:

- message = Component returned failure code: 0x80570019 (NS_ERROR_XPC_CANT_CREATE_WN) [nsIJSCID.createInstance]
- fileName = undefined
- lineNumber = 14
- stack = @undefined:14:undefined|@http://resourcehelloworld-addon/index.js:14:25|run@resourcegre/modules/commonjs/sdk/addon/runner.js:145:19|startup/</<@resourcegre/modules/commonjs/sdk/addon/runner.js:86:7|Handler.prototype.process@resourcegre/modules/Promise-backend.js:920:23|this.PromiseWalker.walkerLoop@resourcegre/modules/Promise-backend.js:799:7|this.PromiseWalker.scheduleWalkerLoop/<@resourcegre/modules/Promise-backend.js:738:39|Promise*this.PromiseWalker.scheduleWalkerLoop@resourcegre/modules/Promise-backend.js:738:7|this.PromiseWalker.schedulePromise@resourcegre/modules/Promise-backend.js:762:7|this.PromiseWalker.completePromise@resourcegre/modules/Promise-backend.js:705:7|handler@resourcegre/modules/commonjs/sdk/addon/window.js:56:3|
- toString = function () /* use strict */ toString



via Chebli Mohamed