Posts

Showing posts with the label Javascript

Console Logging For React?

Image
Answer : If you're just after console logging here's what I'd do: export default class App extends Component { componentDidMount() { console.log('I was triggered during componentDidMount') } render() { console.log('I was triggered during render') return ( <div> I am the App component </div> ) } } Shouldn't be any need for those packages just to do console logging. Here are some more console logging "pro tips": console.table var animals = [ { animal: 'Horse', name: 'Henry', age: 43 }, { animal: 'Dog', name: 'Fred', age: 13 }, { animal: 'Cat', name: 'Frodo', age: 18 } ]; console.table(animals); console.trace Shows you the call stack for leading up to the console. You can even customise your consoles to make them stand out console.todo = function(msg) { console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘...

Bootstrap Toast Does Not Show Up

Answer : You need to put the valid option. i:e show, hide or a callback function . See - https://getbootstrap.com/docs/4.2/components/toasts/. $('.toast').toast('show'); <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header"> <img height="200px" width="200px" src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Phoenicopterus_ruber_in_S%C3%A3o_Paulo_Zoo.jpg" class="rounded mr-2" alt="..."> <strong class="mr-auto">Boots...

Bulk Upsert In MongoDB Using Mongoose

Answer : Not in "mongoose" specifically, or at least not yet as of writing. The MongoDB shell as of the 2.6 release actually uses the "Bulk operations API" "under the hood" as it were for all of the general helper methods. In it's implementation, it tries to do this first, and if an older version server is detected then there is a "fallback" to the legacy implementation. All of the mongoose methods "currently" use the "legacy" implementation or the write concern response and the basic legacy methods. But there is a .collection accessor from any given mongoose model that essentially accesses the "collection object" from the underlying "node native driver" on which mongoose is implemented itself: var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var sampleSchema = new Schema({},{ "strict": false }); va...

Bootstrap-select Add Item And Select It

Answer : You have a typo. Instead of: $('#myselect').append('<option val="'+newitemnum+'">'+newitemdesc+'</option>'); You need: $('#myselect').append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); Here is a JSFiddle demo: http://jsfiddle.net/xbr5agqt/ The "Add and select 'Soy Sauce' option" button does the following: $("#myselect").append('<option value="'+newitemnum+'">'+newitemdesc+'</option>'); $("#myselect").val(4); $("#myselect").selectpicker("refresh"); One slightly faster approach (used by the "Add and select 'Relish' option" button) is to append the new <option> element with the selected attribute already applied: $("#myselect").append('<option value="'+newitemnum+'" selected=...

Cancel All Subscriptions And Asyncs In The ComponentWillUnmount Method, How?

Answer : You can use isMounted React pattern to avoid memory leaks here. In your constructor: constructor(props) { super(props); this._isMounted = false; // rest of your code } componentDidMount() { this._isMounted = true; this._isMounted && this.getImage(this.props.item.image); } in your componentWillUnmount componentWillUnmount() { this._isMounted = false; } While in you getImage() async getImage(img) { let imgUri = await Amplify.Storage.get(img) let uri = await CacheManager.get(imgUri).getPath() this._isMounted && this.setState({ image: { uri }, ready: true }) } A recommend approach to use Axios which is based cancellable promise pattern. So you can cancel any network call while unmounting the component with it's cancelToken subscription . Here is resource for Axios Cancellation From the React blog Just set a _isMounted property to true in componentDidMount and set it to false in ...

Convert JavaScript Object Into URI-encoded String

Answer : Please look closely at both answers I provide here to determine which fits you best. Answer 1: Likely what you need: Readies a JSON to be used in a URL as a single argument, for later decoding. jsfiddle encodeURIComponent(JSON.stringify({"test1":"val1","test2":"val2"}))+"<div>"); Result: %7B%22test%22%3A%22val1%22%2C%22test2%22%3A%22val2%22%7D For those who just want a function to do it: function jsonToURI(json){ return encodeURIComponent(JSON.stringify(json)); } function uriToJSON(urijson){ return JSON.parse(decodeURIComponent(urijson)); } Answer 2: Uses a JSON as a source of key value pairs for x-www-form-urlencoded output. jsfiddle // This should probably only be used if all JSON elements are strings function xwwwfurlenc(srcjson){ if(typeof srcjson !== "object") if(typeof console !== "undefined"){ console.log("\"srcjson\" is not a JSON object"); ret...

Can't Change Default Nuxt Favicon

Answer : I found the solution, but it's kind of tricky and it's a little far from logic. the size of the favicon should be 32*32 pixels or nuxt will load the default favicon itself. and about my tries, it's enough to have a file in your static folder and give the path to nuxt.config.js . but I'm still confused with the solution. Have you tried replace type: 'image/x-icon' with type: 'image/png' ? The infos about this attribute and tag generally can be read here nuxt will convert object like { head: { link: [{ rel: 'icon', type: 'image/png', href: '/favicon.png' }] }} to <head> <link rel='icon' type='image/png' href='/favicon.png'> </head> So you can use any attributes listed in the article above.

400x Sorting Speedup By Switching A.localeCompare(b) To (ab?1:0))

Answer : A great performance improvement can be obtained by declaring the collator object beforehand and using it's compare method. EG: const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); arrayOfObjects.sort((a, b) => { return collator.compare(a.name, b.name); }); Here's a benchmark script comparing the 3 methods: const arr = []; for (let i = 0; i < 2000; i++) { arr.push(`test-${Math.random()}`); } const arr1 = arr.slice(); const arr2 = arr.slice(); const arr3 = arr.slice(); console.time('#1 - localeCompare'); arr1.sort((a, b) => a.localeCompare( b, undefined, { numeric: true, sensitivity: 'base' } )); console.timeEnd('#1 - localeCompare'); console.time('#2 - collator'); const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); arr2.sort((a, b) => collator.compare(a, b)); console.timeEnd('#2 - collator'); con...

Add Field Separately To Firestore Document

Answer : Build a DocumentReference to the document you want to update, then use the update() method on the DocumentReference to indicate only the fields to be added or changed. Pass it an object with only properties that match the fields to add or change.

Angular: Scroll Dynamic Element Into View Knowing Only Its ID

Answer : You want the id to be on the actual item that the ng-for creates, not the ng-for itself. That would eliminate the need for any extra logic when passing data to the list from the component. // inside ngAfterViewInit() to make sure the list items render or inside ngAfterViewChecked() if you are anticipating live data using @Inputs const itemToScrollTo = document.getElementById('item-' + id); // null check to ensure that the element actually exists if (itemToScrollTo) { itemToScrollTo.scrollIntoView(true); } <div class="list" *ngFor="let item of functionThatGetsItems(); let i = index"> <div class="list-item" id="item-{{i}}"> <div class="title"> {{ item.title }} </div> <div class="content"> {{ item.content }} </div> </div> </div> This is not strictly angular, but you could do document.querySelector('#MyList31'...

Add CSS Rule Via JQuery For Future Created Elements

Answer : This should work: var style = $('<style>.class { background-color: blue; }</style>'); $('html > head').append(style); When you plan to remove elements from the DOM to re-insert them later, then use .detach() instead of .remove() . Using .detach() will preserve your CSS when re-inserting later. From the documentation: The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time. Here is some JavaScript code I wrote before to let me add, remove and edit CSS: function CSS(sheet) { if (sheet.constructor.name === 'CSSStyleSheet' ) this.sheet = sheet; else if (sheet.constructor.name === 'HTMLStyleElement') this.sheet = sheet.sheet; else throw new TypeError(sheet + ' is not a StyleSheet'); } CSS.prototype = {...

Convert XML To JSON (and Back) Using Javascript

Answer : I think this is the best one: Converting between XML and JSON Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit. https://github.com/abdmob/x2js - my own library (updated URL from http://code.google.com/p/x2js/): This library provides XML to JSON (JavaScript Objects) and vice versa javascript conversion functions. The library is very small and doesn't require any other additional libraries. API functions new X2JS() - to create your instance to access all library functionality. Also you could specify optional configuration options here X2JS.xml2json - Convert XML specified as DOM Object to JSON X2JS.json2xml - Convert JSON to XML DOM Object X2JS.xml_str2json - Convert XML specified as string to JSON X2JS.json2xml_str - Convert JSON to XML s...

Conditional Display Of Html Element Forms

Answer : What worked: You had two buttons, both visible in the beginning. And on click of one button, you hid a div , and made another visible. Now you need a situation when the divs should be hidden in the beginning, and then show when you click a button. By default, for all elements where a explicit visibility attribute is not given, visibility is considered to be visible . To make the button invisible, you need to add visibility:hidden to the button. You can do it two ways: In the code for the div s, make then "invisible by default" by adding style='visibility:hidden' . Add another javascript function that is called on load of the page, and makes both the divs invisible: function hideBoth() { document.getElementById("cont1").style.visibility="hidden"; document.getElementById("cont2").style.visibility="hidden"; } Call it on load of your page: <body onload='hideBoth()'> This line: document.get...

Callback Returns Undefined With Chrome.storage.sync.get

Answer : The chrome.storage API is asynchronous - it doesn't return it directly, rather passing it as an argument to the callback function. The function call itself always returns undefined . This is often used to allow other methods to run without having to wait until something responds or completes - an example of this is setTimeout (only difference is that it returns a timer value, not undefined ). For example, take this: setTimeout(function () { alert(1); }, 10000); alert(0); Because setTimeout is asynchronous, it will not stop all code until the entire function completes, rather returning initially, only calling a function when it is completed later on - this is why 0 comes up before 1. For this reason, you cannot simply do something like: // "foo" will always be undefined var foo = asyncBar(function (e) { return e; }); Generally, you should put what you want to do in your callback (the function that is called when the asynchronous function i...

Call Function With SetInterval In JQuery?

Answer : To write the best code, you "should" use the latter approach, with a function reference: var refreshId = setInterval(function() {}, 5000); or function test() {} var refreshId = setInterval(test, 5000); but your approach of function test() {} var refreshId = setInterval("test()", 5000); is basically valid, too (as long as test() is global). Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library. First of all: Yes you can mix jQuery with common JS :) Best way to build up an intervall call of a function is to use setTimeout methode: For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this: function test(){ console.log('test called'); setTimeout(test, 5000); } Finally you have to trigger the function once: $(document).re...

Convert SVG Path D Attribute To A Array Of Points

Answer : The SVGPathElement API has built-in methods for getting this info. You do not need to parse the data-string yourself. Since you stored a selection for your line as a variable, you can easily access the path element's api using myLine.node() to refer to the path element itself. For example: var pathElement = myLine.node(); Then you can access the list of commands used to construct the path by accessing the pathSegList property: var pathSegList = pathElement.pathSegList; Using the length property of this object, you can easily loop through it to get the coordinates associated with each path segment: for (var i = 0; i < pathSegList.length; i++) { console.log(pathSegList[i]); } Inspecting the console output, you will find that each path segment has properties for x and y representing the endpoint of that segment. For bezier curves, arcs, and the like, the control points are also given as x1 , y1 , x2 , and y2 as necessary. In your case, regardless of whether yo...

Can I Use Javascript To Dynamically Change A Video's Source?

Answer : Sure, You can set the src attribute on the source element: document.querySelector("#myVideoTag > source").src = "http://example.com/new_url.mp4" Or using jQuery instead of standard DOM methods: $("#myVideoTag > source").attr("src", "http://example.com/new_url.mp4"​​​​)​ Then you need to call the load method on the video element: videoElement.load() I have faced this problem several times and based on previous experience and digging I can suggest these options: replace video tag completely yes, just re-insert <video> element with new sources. It's straightforward, but effective approach. Don't forget to re-initialize event listeners. assign video URL to video.src this I saw a lot in answers here, on stackoverflow, and also in sources on github. var video = document.getElementById('#myVideo'); video.src = newSourceURL; It works, but you cannot provide browser opt...

Convert Inline SVG To Base64 String

Answer : Use XMLSerializer to convert the DOM to a string var s = new XMLSerializer().serializeToString(document.getElementById("svg")) and then btoa can convert that to base64 var encodedData = window.btoa(s); Just prepend the data URL intro i.e. data:image/svg+xml;base64, and there you have it. You can do it relatively straightforwardly as follows. The short version is Make an image not attached to the dom Set its size to match the source svg base64 encode the source svg , append the relevant data, set img src Get the canvas context; .drawImage the image <script type="text/javascript"> window.onload = function() { paintSvgToCanvas(document.getElementById('source'), document.getElementById('tgt')); } function paintSvgToCanvas(uSvg, uCanvas) { var pbx = document.createElement('img'); pbx.style.width = uSvg.style.width; pbx.style.height = uSvg.style.height; pbx.src = 'data:...

Create XML In Javascript

Answer : Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser. JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways: 1. Creating a new XML DOM object var xmlDoc = document.implementation.createDocument(null, "books"); The first argument can contain the namespace URI of the document to be created, if the document belongs to one. Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument 2. Fetching an XML file with XMLHttpRequest var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { var xmlDoc = xhttp.responseXML; //important to use responseXML here } xhttp.open("GET", "books.xml", true); xhttp.send(); 3. Parsing a string containing serialized XML var xmlString = "<root></root>"; var parser = new DOMParser(); var xmlDoc = pa...

Copy Image To Clipboard From Browser In Javascript?

Answer : No, you can't copy images to the clipboard. Copying anything to the clipboard is a security limitation of every browser, but you may able to copy text to the clipboard in IE if they have the proper security settings. Here Mozilla lists some of the problems caused by programmatic access to the clipboard. Yes, most of the scripts supports text only. http://forums.mozillazine.org/viewtopic.php?f=25&t=1195035&start=0 The above site also discussing the same issue. The following site said related to security issues, http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard but this won't work in latest version of Mozilla. The last answer is from 2010 and browsers have changed a lot since then. With this simple function, you can copy whatever you want (text, images, tables, etc) (on your page) to the clipboard. The function receive the element id or the element itself. function copyElementToClipboard(element) { window.getSelection().removeAllRanges...