Saturday, May 14, 2016

JavaScript Tips



https://www.includehelp.com/code-snippets/javascript-to-detect-whether-page-is-load-on-mobile-or-desktop.aspx
var isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);


https://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/
window.addEventListener ?
window.addEventListener("load",yourFunction,false) :
window.attachEvent && window.attachEvent("onload",yourFunction);

One big tip I can offer other “casual” javascript coders, since many times a script must be executed after a page is loaded, is to STOP using window.onload=your_function;
The reason for this is simple – you should be APPENDING your script to the page loaded hook, not CLOBBERING any existing scripts that may be already attached. The “window.onload” method can only hook one function at a time and these days it’s common to use several third party scripts on a site. If you are not careful, you may be left scratching your head why something stopped working – because you accidentally stopped it from loading.
I think what's probably happening here is that your window.onload is being overridden later, check to make sure that it's not via things like <body onload="">
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.
function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6
Update: Since ES6, you can simply use the spread syntax when calling the function:
func(...arr);
Since ES6 also if you expect to treat your arguments as an array, you can also use the spread syntax in the parameter list, for example:
function func(...args) {
  args.forEach(arg => console.log(arg))
}


https://stackoverflow.com/questions/7139103/open-page-in-new-window-without-popup-blocking
A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.
In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.
https://stackoverflow.com/questions/18587633/dynamic-link-with-javascript
<a href="#" id="myUniqueLinkId">name of link</a>
JS
var month = (new Date()).getMonth();
var myURL = 'http://domain.tld/myLocalFile.php?month=' + month + '&param=1';
document.getElementById('myUniqueLinkId').href = myURL;
Or alternatively just handle it completely at runtime:
<a onclick="window.location='http://domain.tld/myLocalFile.php?month=' 
   + (new Date()).getMonth();return false;" href="#">name of link</a>

Get last part of URI
https://stackoverflow.com/questions/16237780/get-last-part-of-uri/16237825
This is a bit shorter, but your solution is definitely a correct one.
var url = window.location.pathname;
var urlsplit = url.split("/").slice(-1)[0];
Or, as PSR says, you could use substr:
var url = window.location.pathname;
url.substr(url.lastIndexOf('/') + 1);
var action = window.location.pathname.split("/").slice(-1)[0];
document.title = "111111"
http://stackoverflow.com/questions/260857/changing-website-favicon-dynamically
 var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'http://www.stackoverflow.com/favicon.ico';
    document.getElementsByTagName('head')[0].appendChild(link);
https://stackoverflow.com/questions/33938178/set-location-pathname-and-location-search-together
Set location.pathname and location.search together?
Just set the location (or location.href):
location = "/abc?name=test";
Since it's a relative URL, the protocol and host will be unchanged.

https://ourcodeworld.com/articles/read/139/all-you-need-to-know-about-conditional-html-comments
Selectors
https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll
var el = document.querySelector('#test');    //return an element with id='test'
var matches = el.querySelectorAll('div.highlighted > p'); // return a NodeList of p wrapped in a div with attribute class "highlighted"
https://developer.mozilla.org/en-US/docs/Web/CSS/Child_selectors
selector1 > selector2 { style properties }
http://www.sitepoint.com/web-foundations/descendant-selector-css-selector/
ul li {
  ⋮ declarations
}
not selector
https://developer.mozilla.org/en-US/docs/Web/CSS/:not
p:not(.classy) { color: red; }
body :not(p) { color: green; }
.reMode_hover:not(.reMode_selected):hover{}

XPath
https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript
var paragraphCount = document.evaluate( 'count(//p)', document, null, XPathResult.ANY_TYPE, null );
http://stackoverflow.com/questions/14248063/xpath-to-select-element-by-attribute-value
/Employees/Employee[@id='4']

// can be very slow because it searches the entire document for matching nodes. If the structure of the documents you're working with are going to be consistent, you are probably best off using a full path

http://stackoverflow.com/questions/13125817/how-to-remove-elements-that-were-fetched-using-queryselectorall
.querySelectorAll returns a frozen NodeList. You need to iterate it and do things.
Array.prototype.forEach.call( element, function( node ) {
    node.parentNode.removeChild( node );
});
Even if you only got one result, you would need to access it via index, like
elements[0].parentNode.removeChild(elements[0]);
To remove an element you do this:
el.parentNode.removeChild(el);

function exec(){
  for(var i=0;i<5;i++){
   setTimeout(function(){
     console.log(new Date());   //It's you code
   },(i+i+1)*1000);
  }
}

setTimeout - one time
setInterval - repeated
 The number the console shows is the return value of setTimeout and is the ID of that timeout (so that you can cancel it). 
http://stackoverflow.com/questions/9136261/how-to-make-a-setinterval-stop-after-some-time-or-after-a-number-of-actions
var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 60){
        clearInterval(interval);
    }
    //do whatever here..
}, 2000); 
If you want to stop it after a set time has passed (e.g. 1 minute) you can do:
var startTime = new Date().getTime();
var interval = setInterval(function(){
    if(new Date().getTime() - startTime > 60000){
        clearInterval(interval);
        return;
    }
    //do whatever here..
}, 2000); 
<script>
//<![CDATA[
document.write("something here");
//]]>
</script>

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts