Tuesday, February 17, 2015

Few usefull tricks


An HTML element with an ID creates a JavaScript global with the same name
Surprising but true, and it's done by modern browsers as a means of backwards compatibility:

HTML: 

<div id="someInnocentDiv"></div>
  

JS:

console.log(someInnocentDiv);  // <div id="someInnocentDiv"></div>



 You can read the text at any XY coordinate on a webpage


var x = 50, y = 100;
var range = document.caretRangeFromPoint(x, y);
if(range) {
    range.expand('word');
    var word = range.startContainer.textContent.substring(range.startOffset, range.endOffset);
    console.log(word);
}


A cross-browser compatible way of doing this: http://jsfiddle.net/heZ4z/


 You can base64 encode files dropped onto the document from your desktop


document.ondrop = function (e) {
    e.preventDefault();  // prevent browser from trying to run/display the file
    var reader = new FileReader();
    reader.onload = function(e) {
      console.log(e.target.result);  // base64 encoded file data!
    };
    reader.readAsDataURL(e.dataTransfer.files[0]);
}


This only works in recent browsers that support the new HTML5 File API:https://developer.mozilla.org/en...



You can quickly run HTML in the browser without creating a HTML file:
Enter this in the address bar: 
data:text/html,<h1>Hello, world!</h1>

(This won't work in IE)

You can make a page's CSS editable in the browser without using JS:

<!DOCTYPE html>
<html>
<body>
<style style="display:block" contentEditable>
body { color: blue }
</style>
</body>
</html>

(This also won't work in IE)

You can have the browser parse a URL for you like this:

var a = document.createElement('a');
a.href = url;

// any property of window.location works here:
document.write('The hostname of ' + url + ' is ' + a.hostname);

(Works in all major browsers)

You can invalidate a URL in the browser's cache by sending a PUT method xmlhttprequest to it:

var xhr = window.XMLHttpRequest ?
    new XMLHttpRequest() :
    new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('PUT', url);
xhr.send(null);

(Works in all major browsers)

You can put multiple statements in an 
if
 block without using curly brackets like this:

if (confirm("Do you wish to see two alerts?"))
  alert(1), alert(2);

(Works in all major browsers)

No comments:

Post a Comment