Tech blog to share information.

April 23, 2018

classList Api - Manipulating CSS classes Javascript Way

April 23, 2018 Posted by tj cool , , No comments
classlist
Javascript has been around from many years and its core of web development. Whether its Dom manipulation, validation or making ajax request, javascript is always there. But all those years we have not seen game changing changes in javascript and may be that is a reason client-side development of client-side framework started. We all know Jquery and understands why it becomes backbone of web development so quickly.

But, from last couple of years Html5 has brought super fun to javascript development by introducing new Api and classList is one of them.

What is classListApi ?

The classList API provides methods and properties to manage class names of DOM elements. Using it, we can perform operations such as adding and removing classes, or checking if a given class is present on an element. The classList API exposes these methods and properties via an attribute of the DOM element, called classList.
The Element.classList is a read-only property which returns a live DOMTokenList collection of the class attributes of the element.Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via “ element.className.”

Syntax

const elementClasses = elementNodeReference.classList;

Methods

add( String [, String [, ...]] )

Simply supply the class you want to add as an argument to the add() method. If these classes already exist in attribute of the element, then they are ignored.
elem.classList.add("class1");
elem.classList.add("class2");
elem.classList.add("class1","class2");

remove( String [, String [, ...]] )

Remove specified class values. Also if you try to removing a class that does not exist, it won’t throw any error.
div.classList.remove("class1");
elem.classList.remove("class1","class2");

toggle( String [, force] )

Toggle come with two flavors
  1. String (classname):  If class exists then remove it and return false, if not, then add it and return true.
  2. Force (True/False): If force is set to true, the class will be added but not removed. If it’s false, the opposite will happen — the class will be removed but not added.
div.classList.toggle("visible");
div.classList.toggle("visible", i < 10 );

contains( String )

Checks if specified class value exists in class attribute of the element. This method returns a Boolean true or false when checking for the presence of a class in the list.It is very useful when you want to check if particular class exists or not.
div.classList.contains("class1")
if(div.classList.contains('class1') {
    div.classList.remove('class1');
}
References:
Complete classList Api Method List
classList Api Stackoverflow Discussions



April 20, 2018

Handling Bootstrap conflicts with Salesforce Styles!

April 20, 2018 Posted by tj cool , , , , , No comments
banner

Bootstrap is the one of most popular CSS framework we have on web an it has been used in nearly all web technologies. With the evolution of Lightning, Salesforce has also introduced UI framework known as Lightning Design System (recommended for SF apps).With the Lightning Design System, you can build custom applications with a look and feel that is consistent with the core features of Salesforce and it looks cool too.

When you have already developed app in Classic i.e. Visualforce pages + Apex and now if you are moving it to Lightning Experience in a iterative manner, then can be a situation where you are using both frameworks i.e. SLDS (as per new development) and Bootstrap CSS/Component from Old development.

As we have two well crafted ideas together, so there will be creativity or can say implementation conflicts. So , when you have common component that shares Bootstrap as well as SLDS/LDS, you will experience mess of styles (this happened to all of  us or atleast i have experienced it).
How to handle conflict of Bootstrap CSS with Salesforce LDS or classic classes ?

Solution 1

We can resolve this conflict (and keep both of them happy). As per our transition we are moving from Bootstrap > LDS, so will try to give unique namespace to Bootstrap styles. To do so, we can use {LESS} compiler.
{LESS} is a CSS pre-processor that lets you change variables before compiling to CSS. Click Here to know more.


Back to our problem , to fix Bootstrap conflict issue, we will be using LESS. Now Less will add prefix to all Bootstrap CSS with a class name. Follow Steps for same.

  1. Download less compiler. Download
  2. Create &lt;filename>.less file, containing lines as per below syntax.
Syntax:
.&lt;prefix-name> {
        @import (less) 'bootstrap.css'; /*Bootstrap CSS name*/
        @import (less) 'bootstrap-theme.css';  /* optional */
}
Example:
        Filename: Bootstrap.less

.bootstrap-ae{
        @import (less) 'bootstrap.css'; /*Bootstrap CSS name*/
        @import (less) 'bootstrap-theme.css';  /* optional */
}
  1. Compile &lt;filename>.less into &lt;output>.css , using below command line:
Example:  lessc Bootstrap.less bootstrap-ae.css

  1. To use Bootstrap CSS, wrap your HTML elements inside div.
Example
&lt;div class="bootstrap-ae">
   &lt;!-- Any HTML here will be styled with Bootstrap CSS -->
&lt;/div>

  1. Open  new bootstrap file in text editor. You will notice that .&lt;prefixes>(in my case it .bootstrap-ae)  prefixes body, html elements as well (which is not good as it’s not possible for a class to prefix the body, html).  As we want these styles to apply to just the class, we can simply remove prefixes applied to body and html.

  1. You're done!

Solution 2

Same trick is applicable to Salesforce Lightning Design system as well. Lightning Salesforce Design System allows you to generate name spaced styles. In fact you will need to wrap your HTML in &lt;div class="my-slds">.
Click here to generate style

Step 1: Select and enter basic details. Check below screenshot.
Step1

Step 2 : Click on “Generate” button. This generate ready to use style sheet for you.
Step2

Creativity comes from a conflict of ideas.
- Donatella Versace -

I hope this is helpful. Thank you for reading. Happy Programming Smile

April 19, 2018

Google Chrome : Developer Console Time Saving Tips

April 19, 2018 Posted by tj cool , , , , No comments

As a web developer,designer we rely a lot on browsers tools. Some tools are inbuilt and some we install as an add on. But on top of that, using tool correctly or i will say using tool more productively is very important. This save our lot of time. On the same front there is one tool that we all uses a lot is “Browser Developer Console”. And Today we will check some of the time saving features of “Google Chrome Developer Console”.
Below are some handful and time saving tips and tricks of developer console. Take a look. Smile
  • Quick file switching : Open Developer(F12) and  Press Ctrl + P. Search box will popup, now  to quickly search for, and open any file in your project type the name of file. File will be filtered and shown as below.
File Switch
  • Search within source code: Searching method, snippet,string in loaded javascript is important. So to search in all files loaded on the page for a specific string, hit Ctrl + Shift + F. Type the string you want to search for and Hit Enter. You will get list of all occurrences of string. This method of searching also  supports Regular expressions as well.
SearchWithinSource


  •  Jump to Line: Say you have opened any file via File switching and now you want to jump on particular line(if you know line number). Then instead of scrolling scrollbar just hit  Ctrl + G
JumpToLine


  • Compare Similar Data Objects: The table() method provides an easy way to view objects and arrays that include similar data. When called, it will take the properties of an object and create a header. The row data then comes from each index's properties value.
    console.table([{a:1, b:2, c:3}, {a:"foo", b:false, c:undefined}]);
    console.table([[1,2,3], [2,3,4]]);
console table display
  • Use multiple carets & selections :  OK. Now you have openedWhile editing a file you can set multiple carets by holding Ctrl and clicking where you want them to be, thus allowing you to write in many places at once.
MultipleSelectClick

  • Measure execution times :  The time() method starts a new timer and is very useful to measure how long something took. Pass a string to the method to give the marker a name. When you want to stop the timer, call timeEnd() and pass it the same string passed to the initializer. The console then logs the label and time elapsed when the timeEnd() method fires.
console.time("Array initialize");
var array= new Array(1000000);
for (var i = array.length - 1; i >= 0; i--) {
    array[i] = new Object();
};
console.timeEnd("Array initialize");

          • Select next occurrence: When we modify any method and if it is big, finding occurrences or changing it is one tedious job. So if you want to perform similar activity, then you press Ctrl + D  while editing files in the Sources Tab, the next occurrence of the current word will be selected. You can also as edit them simultaneously.

          • Run Snippets Of Code From Any Page : If you have small utilities or debugging scripts which you find yourself using repeatedly on multiple pages, consider saving the scripts as snippets. 
            • Step 1 - Create Snippet : To create a snippet, open the Sources panel, click on the Snippets tab, right-click within the Navigator, and then select New.

            • Step 2 - Save Changes : Enter your code in the editor and save changes 
            • Step 3 - Run Script : Right-click on the snippet filename (in the pane on the left that lists all your snippets) and select Run.




          There are other tips as well. I will try to cover up in other post. Thank you

          References
          1. I am not original creator of gif images.
          2. Chrome Dev Tools


          October 17, 2015

          : Part 1 : Working With Jquery Validation Plugin

          October 17, 2015 Posted by tj cool , No comments
          This jQuery plugin makes clientside form validation simple, effective and easy. It makes a good choice for  scratch application as well as when you’re trying to integrate something into an existing application with lots of existing markup. Jquery validation comes with pre-defined set of validation at the same time developer can easily extend or introduces new validations.

          For the latest stable release of jquery visit : Jquery CDN

          Getting Started 

          Step 1  : Add reference of jquery and jquery validation plugin.To get latest uri of validation plugin visit : JSCDN. For the demo i am refereing following uri



          Initializing Jquery Validation 

          Validator 

          The validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically.

          Writing Basic form Validation

          i have created following examples, to demonstrate jquery validation 

          Field Required

          October 11, 2012

          Task Parallel Libraray vs Threading

          October 11, 2012 Posted by tj cool , , No comments
          1. Create a Console Application in VS2010 name TaskParallelLibraray 2. Include Following Name Spaces in Program.CS
          
          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using System.Threading;
          using System.Diagnostics;
          using System.Collections;
          using System.Threading.Tasks;
          
          
          3 Write Below code inside Class Program in Program.CS
          static void Main(string[] args)
             {
                try
                 {
                    // CREATE A TREE WITH ~1023 NODES
                    Tree tree = Tree.CreateSomeTree(10, 1);
          
                    // START THE STOP WATCH
                    Stopwatch sw = Stopwatch.StartNew();
                          
                    //WALK THE TREE
                    WalkTree(tree);
          
                    // GET THE TIME ELAPSED
                     Console.WriteLine("Time Elapsed = " + sw.ElapsedMilliseconds.ToString());
                          
                    // WAIT TO SEE RESULTS
                    Console.ReadLine();
                    }
                    catch (Exception ex)
                    {
                          Console.WriteLine(ex.Message);
                          Console.Read();
                    }
                 }
          
                  // WALK THE TREE USING RECURSION
                  static void WalkTree(Tree tree)
                  {
                      //RETURN WHEN THERE ARE NO MORE CHILDRENS
                      if (tree == null) return;
          
                      #region USING TRADITIONAL SEQUENTIAL APPROACH
          
                      WalkTree(tree.Left);
                      WalkTree(tree.Right);
          
                      #endregion
          
                      #region USING THREADING
          
                      // ************ PROCESS EVERY NODE USING THREADING
                      // THIS MAY GIVE FOLLOWING EXCEPTION
                      // An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll
                      // BECAUSE WHENEVER NEW THREAD CREATED IT REQUIRE TO STORE PREVIOS THREAD STATE WHICH IS MORE MEMORY CONSUMING IN THIS EXAMPLE
          
                      //Thread left = new Thread(() => WalkTree(tree.Left));
                      //left.Start();
                      //Thread right = new Thread(() => WalkTree(tree.Right));
                      //right.Start();
          
                      //// WAIT/JOIN ON BOTH OF THEM TO COMPLETE
                      //left.Join();
                      //right.Join();
          
                      //************ Process every node using thread - End
          
                      #endregion
          
                      #region USING TASKS PARALLEL LIBRARY THAT IS USING TASK
          
                      //Task left = new Task(() => WalkTree(tree.Left));
                      //left.Start();
                      //Task right = new Task(() => WalkTree(tree.Right));
                      //right.Start();
                      //left.Wait();
                      //right.Wait();
          
                      #endregion
          
                      ProcessItem(tree.Data);
                  }
          
                  // SPINWAIT PUTS PROCESSOR IN TIGHT LOOP, WITH LOOP COUNT SPECIFIED IN ITERATION  PARAMETER
                  private static int ProcessItem(int p)
                  {
                      // THIS IS WHERE COMPUTE/BUSINESS LOGIC GOES
                      Thread.SpinWait(4000000); // CONTRAST WITH THREAD.SLEEP
                      return p; // not used
                  }
          
          
          
          4. Add Class name Tree.cs and paste following code
          
          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          
          namespace TaskParallelLibraray
          {
              public class Tree
              {
                  public Tree Left = null;
                  public Tree Right = null;
          
                  public int Data = 0;
          
                  // Tree of depth 3 and start of 1
                  // each node will have children left and right
                  // value will increase based on depth
                  //       1
                  //   2       2
                  // 3   3   3   3
                  //4 4 4 4 4 4 4 4
                  internal static Tree CreateSomeTree(int depth, int start)
                  {
                      Tree root = new Tree();
                      root.Data = start;
          
                      if (depth > 0)
                      {
                          root.Left = CreateSomeTree(depth - 1, start + 1);
                          root.Right = CreateSomeTree(depth - 1, start + 1);
                      }
                      return root;
                  }
              }
          }
          
          5. Run this program in a machine having dual core or core to duo processor and c the out put Almost all our servers are having multicore processor :D so performance will be great on servers rather than out Desktops Reference :MSDN