Javascript supports at most 53 bit integers. What this means is that integers larger than 53 bits lose precision. This article will explain how to handle addition with integers larger than 53 bits in javascript. |
I'm looking for a Mathematical solution that deals with really (long, big, huge, storms) numbers. I haven't found anything yet, But I don't wanna think that this problem hasn't be solve at this time. I'm looking for an easy Number solution, like Microsoft Excel Precision (30 decimals), or a BigInteger (Java) solution. in Javascript of course. |
JavaScript is only capable of handling 53-bit numbers, if you are working with a big number such as Twitter ID, which is using 64-bit number, then you need to find an external library to do that, otherwise, there will be precision lost. |
View in JSFiddle |
<script type="text/javascript" src="big-number.js"></script> <script type="text/javascript"> (function () { var a = new BigNumber("07777777"), b = "888888880"; console.log(a.multiply(b).toString()); console.log(new BigNumber("990").toString()); })(); </script> |
Download Library |
Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts
Saturday, May 25, 2019
How to deal with big numbers in javascript | Extremely large numbers in javascript | Large Number Addition in JavaScript | How to deal with extremly big numbers in javascript |
Saturday, August 11, 2018
Setting Up Recaptcha 2.0 with JavaScript and PHP
reCAPTCHA need to verify bots (automatic system) can't take advantage of your site. reCAPTCHA 2.0 is somewhat different than the old reCAPTCHA. In version 1.0 it required to type text but now in 2.0 it’s simply a click of a button as below image. |
|
The term of verifying front end users is a bit different. A variable named "g-recaptcha-response" is sent through a POST request to your server-side script, and along with your reCAPTCHA secret key that you get when you sign up for your website, you need to pass that secret key along to Google to tell that the user is a bot or not to determine by system. The response from Google is a JSON response on success for failure both case, so that we will be using file_get_contents() and json_decode() to fetch and parse the response and decide that front user is valid or not. |
|
The below is just a HTML form you should create to see captcha in your desired page. The div element with the class of "g-recaptcha" is the element where we want to place our Google captcha (reCAPTCHA). You need to replace data-sitekey with the key you get from google when you sign up for reCAPTCHA (https://www.google.com/recaptcha/intro/index.html). |
<form method="post" enctype="multipart/form-data"> <div class="g-recaptcha" data-sitekey="YOUR_KEY"></div> <button type="submit">CHECK RECAPTCHA</button> </form> |
But I will show another technique how to show reCAPTCHA using JavaScript. Below is a simple script to show how you can integrate reCAPTCHA using JavaScript. But server side validation using PHP. Use need to create an div with ID (suppose, you can create your div with other ID) captcha_container |
<script src='https://www.google.com/recaptcha/api.js'></script> var captchaContainer = grecaptcha.render('captcha_container', { 'sitekey' : 'Your sitekey', 'callback' : function(response) { console.log(response); } }); |
Now time to validate reCAPTCHA from server side. |
<?php $url = 'https://www.google.com/recaptcha/api/siteverify'; $data = array( 'secret' => 'YOUR_SECRET', 'response' => $_POST["g-recaptcha-response"] ); $options = array( 'http' => array( 'method' => 'POST', 'content' => http_build_query($data) ) ); $context = stream_context_create($options); $verify = file_get_contents($url, false, $context); $captcha_success = json_decode($verify); if ($captcha_success->success == false) { echo "<p>You are a bot! Go away!</p>"; } else if ($captcha_success->success == true) { echo "<p>You are not not a bot!</p>"; } |
Friday, January 12, 2018
Print the contents of specific DIV using javascript | jQuery Print Specific div Content demo | How to print selected div instead complete page JQuery | Print specific element using jquery | jQuery Plugin To Print Any Part Of Your Page - Print | Printing selective DOM elements on a page
HTML Element |
<div> <h1>Header</h1> <div class="printable"> <div>Body 1</div> <div class='c2'>Body 2</div> <div class='c2'><h1>Body 3 Inside Printable</h1></div> </div> <div style="margin-top:10px;border-top:1px solid;"> </div> <button>Print</button> </div> |
Styling |
body >div { margin:20px;border:2px solid;padding:7px; } .printable .c2 { padding-left: 30px; } @media print { @page { size: A4 landscape; padding:1cm; } body * { visibility: hidden; } .printable { border:2px solid green;margin:0;left:0;top:0;position:absolute; width:calc(100% - 20px);padding:8px; } .printable, .printable * { visibility: visible; } } |
JavaScript / JQuery part |
document.title = "Need to print some specific area"; $("button").click(function() { var title = document.title; document.title = "Going to print"; window.print(); document.title = title; }); |
And finally LIVE DEMO on JSFiddle |
Sunday, November 19, 2017
JQuery Load Javascript Dynamically | Dynamic JS Loading
JQuery Load Javascript Dynamically | Dynamic JS Loading
var script = document.createElement("SCRIPT"); script.src = '//code.jquery.com/jquery-latest.min.js'; script.type = 'text/javascript'; script.onload = function() { var nj = jQuery.noConflict(true); alert(jn.find("body").length); }; document.getElementsByTagName("head")[0].appendChild(script);
Thursday, November 16, 2017
JavaScript Regex To Match Domain Name | Domain Validator Regex
Below is the required regex to validate any domain name, its simple so you can modify if you need to extend it.
^((http|https):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,10})$
^((http|https):\/\/)?([a-zA-Z0-9_][-_a-zA-Z0-9]{0,62}\.)+([a-zA-Z0-9]{1,10})$
Saturday, November 11, 2017
JavaScript Interval Example | SetInterval And ClearInterval
JavaScript setInterval & clearInterval example:
JSFiddle example link
var i = 3; var interval = setInterval(function() { if (i > 0) { $("div").html("Running " + i--); } else { clearInterval(interval); $("div").html("Stopped"); } }, 2000);
JSFiddle example link
Thursday, November 2, 2017
JavaScript | jQuery Validate Email Address Using Regex Pattern Check
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
And you can check your desired input by:
pattern.test("pritomkucse@gmail.com");
Wednesday, June 21, 2017
JavaScript | jQuery: Manual Ajax Form Submit Using XMLHttpRequest | XMLHttpRequest to Post HTML Form | Upload File Ajax | Submit FormData
It's easy to submit an form using JavaScript ajax request. We also can upload files using ajax form submit. Below is a simple code snippet:
<form name="content_info"> <input type="file" name="file"/> <button type="button" onclick="doPost()">Ajax Submit</button> </form> <script type="text/javascript"> function doPost() { var form = document.forms.namedItem("content_info"); var formData = new FormData(form); //or formData = new FormData(); formData.append("custom_param", "custom_param_value"); var request = new XMLHttpRequest(); request.open("POST", "submit.php", true); request.responseType = "json"; request.onload = function(oEvent) { console.log(request.status); console.log(request); console.log(request.response); alert(request.status); }; request.onerror = function (error) { console.log(error); }; request.setRequestHeader("Custom-Code", "EKKODJIU"); request.send(formData); } </script>
Friday, December 30, 2016
How to insert an item into an array at a specific index javascript
var arr = ["X1", "X2", "X3", "X4", "X5"];
Inserting "X2.2" into position "2" without deleting "0" item
arr.splice(2, 0, "X2.2");
First Array Values:
X1, X2, X3, X4, X5
After insert new value:
X1, X2, X2.2, X3, X4, X5
Create GUID / UUID in JavaScript
<script type="text/javascript"> function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } alert(guid()); </script>
Monday, November 28, 2016
JavaScript noUiSlider Example
Download nouislider.css & nouislider.js before try the example below.
noUiSlider code example
<head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link href="nouislider.css" rel="stylesheet"> <script src="nouislider.js"></script </head> <body> <div style="width: 90%; margin-left: 5%; padding-top: 30px;"> <div class="parent"> <h3> <i>NoUiSlider_1 = <span class="slider_value"></span></i> <input type="button" class="reset_1" value="Reset"/> <input type="button" class="disable disable_1" value="Disable"/> <input type="button" class="enable enable_1" value="Enable" style="display: none;"/> </h3> <div class="slider slider_1"></div> </div> <div class="parent"> <h3> <i>NoUiSlider_2 = <span class="slider_value"></span></i> <input type="button" class="reset_2" value="Reset"/> </h3> <div class="slider slider_2"></div> </div> <div class="parent"> <h3><i>Slider Example</i></h3> <div style="width: 120px;" class="slider-toggle"></div> </div> </div> </body> <script type="text/javascript"> createSimpleSlider(); createToggleSlider(); function createSimpleSlider() { for(var i = 1; i <= 2; i++) { var range = $('.slider_' + i)[0]; noUiSlider.create(range, { start: 40, tooltips: [ true ], connect: [true, false], range: { 'min': 0, 'max': 100 }, format: { to: function ( value ) { return parseInt(value); }, from: function ( value ) { return value; } } }).on('update', function( values, handle ) { var target = $(this.target); var slider_tooltip = target.find(".noUi-handle"); if(values[handle] > 50) { slider_tooltip.addClass("half_way_pass"); } else { slider_tooltip.removeClass("half_way_pass"); } var slider_value = target.closest(".parent").find(".slider_value")[0]; slider_value.innerHTML = values[handle]; }); $('.reset_' + i).click(function() { var target = $(this); target.closest(".parent").find(".slider")[0].noUiSlider.set([15]); }) $('.disable_' + i).click(function() { var target = $(this); target.closest(".parent").find(".slider").attr("disabled", "disabled"); target.hide(); target.closest(".parent").find(".enable").show(); }) $('.enable_' + i).click(function() { var target = $(this); target.closest(".parent").find(".slider").removeAttr("disabled"); target.hide(); target.closest(".parent").find(".disable").show(); }) } } function createToggleSlider() { var toggleSlider = $('.slider-toggle')[0]; noUiSlider.create(toggleSlider, { start: 0, range: { 'min': [0, 1], 'max': 1 }, format: { to: function ( value ) { return parseInt(value); }, from: function ( value ) { return value; } } }); toggleSlider.noUiSlider.on('update', function( values, handle ) { var target = $(this.target); var slider_tooltip = target.find(".noUi-handle"); if(values[handle] > 0) { slider_tooltip.addClass("half_way_pass"); } else { slider_tooltip.removeClass("half_way_pass"); } var slider_value = target.closest(".parent").find(".slider_value")[0]; slider_value.innerHTML = values[handle]; }); } </script>
Friday, March 7, 2014
Native Fullscreen JavaScript/jQuery API
http://johndyer.name/native-fullscreen-javascript-api-plus-jquery-plugin/
My name pritom
jQuery code
$(document).ready(function () { var fullScreenCheck = $("div#main-body").checkFullScreen(); if (fullScreenCheck.enter && fullScreenCheck.exit && fullScreenCheck.fullscreen && fullScreenCheck.change && fullScreenCheck.error) { $(document).bind(fullScreenCheck.change, fullScreenChangeHandler); $(document).bind(fullScreenCheck.error, fullScreenErrorHandler); $(".fsmode").html("Full screen would work..."); $("div#main-body .fullscreen").click(function () { if(document[fullScreenCheck.fullscreen]) { console.log("Going to normal screen..."); document[fullScreenCheck.exit](); } else { console.log("Going to full screen..."); $("div#main-body")[0][fullScreenCheck.enter](); } }) $("div#main-body").click(function () { $(document).trigger("fullscreenchange"); }) $(document).bind("fullscreenchange", function() { if (document[fullScreenCheck.fullscreen]) { $(".fsmode").html("Window is now full screen..."); } else { $(".fsmode").html("Window is now normal screen..."); } }); } else { $(".fsmode").html("Full screen would not work..."); $("div#main-body .fullscreen").remove(); } function fullScreenChangeHandler(event) { $(document).trigger(new $.Event("fullscreenchange")); } function fullScreenErrorHandler(event) { console.log(event.originalEvent); } }) jQuery.fn.checkFullScreen = function () { var enter, exit, fullscreen // support for entering fullscreen var dom = document.createElement('div'); if ('requestFullscreen' in dom) { enter = 'requestFullscreen' // W3C proposal } else if ('requestFullScreen' in dom) { enter = 'requestFullScreen' // mozilla proposal } else if ('webkitRequestFullScreen' in dom) { enter = 'webkitRequestFullScreen' // webkit } else if ('mozRequestFullScreen' in dom) { enter = 'mozRequestFullScreen' // firefox } else if ('msRequestFullscreen' in dom) { enter = 'msRequestFullscreen' // ms } else { enter = null // not supported in this browser } // support for exiting fullscreen if ('exitFullscreen' in document) { exit = 'exitFullscreen' // W3C proposal } else if ('cancelFullScreen' in document) { exit = 'cancelFullScreen' // mozilla proposal } else if ('webkitCancelFullScreen' in document) { exit = 'webkitCancelFullScreen' // webkit } else if ('mozCancelFullScreen' in document) { exit = 'mozCancelFullScreen' // firefox } else if ('msExitFullscreen' in document) { exit = 'msExitFullscreen' // ms } else { exit = null // not supported in this browser } // support for detecting when in fullscreen if ('fullscreen' in document) { fullscreen = 'fullscreen' // W3C proposal } else if ('fullScreen' in document) { fullscreen = 'fullScreen' // mozilla proposal } else if ('webkitIsFullScreen' in document) { fullscreen = 'webkitIsFullScreen' // webkit } else if ('mozFullScreen' in document) { fullscreen = 'mozFullScreen' // firefox } else if ('msFullscreenElement' in document) { fullscreen = 'msFullscreenElement' // ms } else { fullscreen = null // not supported in this browser } if (document["webkitCancelFullScreen"]) { change = "webkitfullscreenchange"; error = "webkitfullscreenerror"; } else if (document["msExitFullscreen"]) { change = "MSFullscreenChange"; error = "MSFullscreenError"; } else if (document["mozCancelFullScreen"]) { change = "mozfullscreenchange"; error = "mozfullscreenerror"; } else { change = "fullscreenchange"; error = "fullscreenerror"; } return { enter: enter, exit: exit, fullscreen: fullscreen, change: change, error: error } };
Sunday, August 4, 2013
Image Data URIs with JavaScript
<img src="your_image.png" id="myimage" />
<canvas width="300" height="300" id="mycanvas" style="display: none;"></canvas>
You will need to create a canvas element with the correct dimensions and copy the image data with the
drawImage
function. Then you can use the toDataURL
function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.
It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.
function getBase64Image(img) {
// Create an empty canvas element
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
return dataURL;
}
var myImage = document.getElementById('myimage');
var imageData = getbase64Image(myImage);
Return like something: "
data:image/png;base64,BASE_64_IMAGE_DATA";
Thursday, April 18, 2013
Get Unix timestamp in Java, Python, Erlang, JavaScript, Php
To Get Unix timestamp value in seconds
Java:
Python:
Erlang:
JavaScript:
Java:
long timestamp = System.currentTimeMillis()/ 1000 |
import time timestamp = int (time.time()) |
{ Mega , Secs , _} = now(), Timestamp = Mega *1000000 + Secs , |
var ts = Math.floor(Date.now()/1000); // You can also use new Date().getTime()/1000 but this one is faster
Php:
$stamp = time();
|
Thursday, April 4, 2013
ckeditor jquery javascript php
https://docs.google.com/file/d/0B5nZNPW48dpFSE5LMk05V2VWSzA/edit?usp=sharing
<?php $ck_id = "ck_editor".time(); if(!isset($ck_className)) { $ck_className = time(); } if(!isset($ck_content)) { $ck_content = ""; } if(!isset($ck_name)) { $ck_name = "ck_name"; } ?> <textarea name="<?php echo $ck_name; ?>"
class="<?php echo $ck_className; ?>"
id="<?php echo $ck_id; ?>"><?php echo $ck_content; ?></textarea>
<script type="text/javascript"> for (var i in CKEDITOR.instances) { if(CKEDITOR.instances[i]) { <?php if(isset($replaceAll) && $replaceAll == true) { ?>CKEDITOR.remove(CKEDITOR.instances[i]); <?php } ?> } } CKEDITOR.replace( '<?php echo $ck_id; ?>', { pasteFromWordRemoveFontStyles : false, fullPage : false, removePlugins : 'elementspath', height : 300, toolbar : [ { name: 'styles', items : [ 'Format','Font','FontSize' ] }, { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike'] }, { name: 'paragraph', items : [ 'NumberedList','BulletedList','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ] }, { name: 'clipboard', items : [ 'Undo','Redo', 'imageUploader' ] }, { name: 'tableoperations', items : [ '-', 'Table', 'TableInsertRowBefore', 'TableInsertRowAfter', 'TableRowDelete', '-', 'TableInsertColumnBefore', 'TableInsertColumnAfter', 'TableColumnDelete', '-', 'TableCellMerge', 'TableCellSplitVertical', 'TableCellSplitHorizontal', 'TableDeleteTable' ] }, { name: 'spellcheck', items: [ 'jQuerySpellChecker' ] } ] }); </script>
Extra plugins made by me "imageUploader" includes in config.js file CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: //config.language = 'fr'; config.uiColor = '#FCFFEB'; config.enterMode = CKEDITOR.ENTER_BR; config.extraPlugins = "imageUploader,tableoperations"; config.pasteFromWordRemoveFontStyles = false;
config.disableNativeSpellChecker = false; /* default spell checking */
};
Make a folder "imageUploader" in plugins folder,
create a file icon.gif and plugin.js
PLUGIN.JS
(function(){ //Section 1 : Code to execute when the toolbar button is pressed var editorCustom; var a = { exec:function(editor){ editorCustom = editor; var theSelectedText = ""; var mySelection = editor.getSelection(); if (CKEDITOR.env.ie) { mySelection.unlock(true); theSelectedText = mySelection.getNative().createRange().text; } else { theSelectedText = mySelection.getNative(); } var backgroundHtmlStyle = " style='background-color: white; "; backgroundHtmlStyle += " height: " + $(window).height() + "px; "; backgroundHtmlStyle += " width: " + $(document).width() + "px; "; backgroundHtmlStyle += " left: 0; opacity: 0.5; position: fixed; top: 0; z-index: 500; ' "; var backgroundHtml = "<div class='ck-editor-image-upload-background' "+backgroundHtmlStyle+"></div>"; $("body").append(backgroundHtml); var uploadFormHtml = "<div class='ck-editor-image-upload'><form id='ck-editor-image-upload-form' accept='utf-8' method=\"post\" enctype=\"multipart/form-data\" accept-charset=\"utf-8\" > "; uploadFormHtml += "<div><span class='1'>Upload Image File</span><span class='2'></span><input type=\"file\" name=\"file\" class=\"file\"/></div>"; uploadFormHtml += "</form></div>"; jQuery.dialogFromHTML("Insert Image", uploadFormHtml, {width: 400}); $(".ck-editor-image-upload").find(".file").bind("change", function() { $("#ck-editor-image-upload-form").attr("action", BASE_URL + "custom_image/upload_ck_editor_image"); $("#ck-editor-image-upload-form").ajaxForm({ beforeSubmit: function() { jQuery.showBackgroundWorkingState(); }, success: function(data) { if(data != "error" && data != "unsupported") { var imageLocation = CK_EDITOR_IMAGE_DIR + data; var imageHtml = "<img src='"+imageLocation+"' alt='"+data+"'/>"; try { editorCustom.insertHtml(imageHtml); } catch (ex) { var content = editorCustom.getData() + "<p>" + imageHtml + "</p>"; editorCustom.setData(content); } } else { jQuery.showWarning("File uploading error, please try again"); } jQuery.closeAllDialog(); jQuery.hideBackgroundWorkingState(); jQuery(".ck-editor-image-upload-background").remove(); }, error: function() { jQuery.showWarning("File uploading error, please try again"); jQuery.closeAllDialog(); jQuery.hideBackgroundWorkingState(); jQuery(".ck-editor-image-upload-background").remove(); } }).submit(); }); } }, //Section 2 : Create the button and add the functionality to it b='imageUploader'; CKEDITOR.plugins.add(b,{ init:function(editor){ editor.addCommand(b,a); editor.ui.addButton('imageUploader',{ label:'Insert Image', icon: this.path + 'icon.gif', command:b }); } }); })();
Subscribe to:
Posts (Atom)