Search This Blog

Sunday, September 8, 2019

Learn Promise async await in Javascript

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
window.addEventListener("load", function(){

});



function execute(a, b, c)
{
  result = a + b;
  console.log(result);
  //c(result);
}
execute(5, 6, function(data)
{
  console.log(data);
});

var promise = new Promise(function(resolve, reject)
{
  //setTimeout(function()
 // {
//     resolve("Success");
 // }, 2000);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     
       resolve(xhttp.response);
    }
};
xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
xhttp.send();
 
 
});

promise.then(function(data)
{
 console.log(JSON.parse(data));
}).catch(function(err)
{
 console.log(err);
});


//async function foo()
//{
 // return Promise.resolve(1);
// }
//foo().then(alert);


async function foo()
{
     let promise = new Promise(function (resolve, reject)
{
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         resolve(xhttp.response);
         }
};
        xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
        xhttp.send();


 });
  let result = await promise;
  alert(result);
 }
 foo();


 async function foos()
 {
   try {
        let response = await fetch("https://5d74dc3dd5d3ea001425b027.mockapi.io/userss");
let result = await response.json();

  } catch(e) {
    // catches errors both in fetch and response.json
    alert(e);
  }


   

 }
 foos();
</script>

</body>
</html>

Friday, September 6, 2019

creating a multi item carousel using bootstrap and sharepoint.

Step1:

Welcome to sharepoint discussion forum, so, Today we are going to discuss how to create a multi item carousel in step by step using bootstrap and sharepoint.

Step 2 : 

First of all, We need a carousel which runs in the bootstrap framework, instead of using third-party plugins to avoid conflict.  Below is the design which we have to implement in sharepoint




Step 3 :

We have to create a separate page to implement this carousel in sharepoint.  goto - All Files->_catalogs> masterpage > assets > html > rockstarsforthemonth.html.

Paste the below code with html markup and  Sharepoint Rest api call

Source Code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!-- This file has been downloaded from Bootsnipp.com. Enjoy! -->
    <title>Rockstars for the month</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet">
 
    <style type="text/css">
        .MultiCarousel { float: left; overflow: hidden; padding: 0px; width:97.5%; position:relative;
        background-color: #ededed;}
    .MultiCarousel .MultiCarousel-inner { transition: 1s ease all; float: left; }
        .MultiCarousel .MultiCarousel-inner .item { float: left;}
        .MultiCarousel .MultiCarousel-inner .item > div { text-align: center; padding:30px; margin:6px 5px 5px 6px; background:#ffffff; color:#666;}
    .MultiCarousel .leftLst, .MultiCarousel .rightLst { position:absolute; border-radius:50%;top:calc(50% - 20px); }
    .MultiCarousel .leftLst { left:14px; }
    .MultiCarousel .rightLst { right:15px; }
    .MultiCarousel .leftLst.over, .MultiCarousel .rightLst.over { pointer-events: none; background:#8a8686;     border-color: #8a8686 }
        .btn-primary {
    color: #fff;
    background-color: #bd5355;
    border-color: #bd5355;
}
     
        .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, .btn-primary:active, .btn-primary.active, .open>.dropdown-toggle.btn-primary {
    color: #fff;
     background-color: #bd5355;
    border-color: #bd5355;
}
        .MultiCarousel h4
        {
            margin-top: 17px;
            color:#aa2225 !important;
            font-size: 24px;
            margin-top: 30px;
            margin-bottom: 0px;
        }
       .MultiCarousel p
        {
            color:#2e2929;
            font-weight: bold;
            font-size:17px;
        }
     
        .MultiCarousel .btn:focus, .MultiCarousel .btn:active:focus, .MultiCarousel .btn.active:focus, .MultiCarousel .btn.focus, .MultiCarousel .btn:active.focus, .MultiCarousel .btn.active.focus {
           outline: none;
        }
        .MultiCarousel .img-circle
        {
            width:150px;
            height: 150px;
        }
        .MultiCarousel .btn {
           padding: 10px 12px 0px 10px;
        }
        .MultiCarousel .fa-chevron-right
        {
        padding-left:2px;


}
    </style>

</head>
<body>
<div class="container" style="margin-top:50px;">
<div class="row">
<div class="MultiCarousel" data-items="1,3,5,6" data-slide="1" id="MultiCarousel"  data-interval="1000">
            <div class="MultiCarousel-inner">
             
     
             
            </div>
            <div class="btn btn-primary leftLst"><i class="fa fa-chevron-left" aria-hidden="true"></i></div>
            <div class="btn btn-primary rightLst"><i class="fa fa-chevron-right" aria-hidden="true"></i></div>
        </div>
</div>

</div>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/4.0/1/MicrosoftAjax.js"></script>

<script type="text/javascript">

$(document).ready(function () {

function retriveListItem()
{
 
    $.ajax
    ({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Rockstars')/items?$select=FileRef/FileRef,EmployeeName,EmployeeDepartment,IsActive&$filter=IsActive eq 1",
        type: "GET",
        headers:
        {
            "Accept": "application/json;odata=verbose",
       
        },
       
        success: function(data) 
        {
   
         $(".MultiCarousel-inner").empty();
            for (var i = 0; i < data.d.results.length; i++) 
            {
                var item = data.d.results[i];               
if(item.EmployeeName !=null && item.EmployeeDepartment !=null)
    {
                 var rockhtml ='<div class="item"><div class="image-flip" ontouchstart="this.classList.toggle("hover");">' +
                             '<div class="mainflip"> <div class="frontside"><div class="card"><div class="card-body text-center">' +
                             '<img class="img-circle" src="' + _spPageContextInfo.webAbsoluteUrl + item.FileRef + '">' +
                             '<h4 class="card-title">' + item.EmployeeName + '</h4> <p class="card-text">' + item.EmployeeDepartment + '</p></div></div></div></div></div></div>'


                  $(".MultiCarousel-inner").append(rockhtml);               
             
                }
                ResCarouselSize();
            }
        },
        error: function(data)
        {
       
            $(".MultiCarousel-inner").empty().text(data.responseJSON.error);
        }
    });
}



    var itemsMainDiv = ('.MultiCarousel');
    var itemsDiv = ('.MultiCarousel-inner');
    var itemWidth = "";

    $('.leftLst, .rightLst').click(function () {
        var condition = $(this).hasClass("leftLst");
        if (condition)
            click(0, this);
        else
            click(1, this)
    });

    ResCarouselSize();
    retriveListItem()
 
    $(window).resize(function () {
   
        ResCarouselSize();
    });

    //this function define the size of the items
    function ResCarouselSize() {
        var incno = 0;
        var dataItems = ("data-items");
        var itemClass = ('.item');
        var id = 0;
        var btnParentSb = '';
        var itemsSplit = '';
        var sampwidth = $(itemsMainDiv).width();
        var bodyWidth = $('body').width();
        $(itemsDiv).each(function () {
            id = id + 1;
            var itemNumbers = $(this).find(itemClass).length;
            btnParentSb = $(this).parent().attr(dataItems);
            itemsSplit = btnParentSb.split(',');
            $(this).parent().attr("id", "MultiCarousel" + id);


            if (bodyWidth >= 1200) {
                incno = itemsSplit[3];
                itemWidth = 284.9;
            }
            else if (bodyWidth >= 992) {
                incno = itemsSplit[2];
                itemWidth = 300;
            }
            else if (bodyWidth >= 768) {
                incno = itemsSplit[1];
                itemWidth = sampwidth / incno;
            }
            else {
                incno = itemsSplit[0];
                itemWidth = sampwidth / incno;
            }
            $(this).css({ 'transform': 'translateX(0px)', 'width': itemWidth * itemNumbers });
            $(this).find(itemClass).each(function () {
                $(this).outerWidth(itemWidth);
            });

            $(".leftLst").addClass("over");
            $(".rightLst").removeClass("over");

        });
         


    }


    //this function used to move the items
    function ResCarousel(e, el, s) {
        var leftBtn = ('.leftLst');
        var rightBtn = ('.rightLst');
        var translateXval = '';
        var divStyle = $(el + ' ' + itemsDiv).css('transform');
        var values = divStyle.match(/-?[\d\.]+/g);
        var xds = Math.abs(values[4]);
        if (e == 0) {
            translateXval = parseInt(xds) - parseInt(itemWidth * s);
            $(el + ' ' + rightBtn).removeClass("over");

            if (translateXval <= itemWidth / 2) {
                translateXval = 0;
                $(el + ' ' + leftBtn).addClass("over");
            }
        }
        else if (e == 1) {
            var itemsCondition = $(el).find(itemsDiv).width() - $(el).width();
            translateXval = parseInt(xds) + parseInt(itemWidth * s);
            $(el + ' ' + leftBtn).removeClass("over");

            if (translateXval >= itemsCondition - itemWidth / 2) {
                translateXval = itemsCondition;
                $(el + ' ' + rightBtn).addClass("over");
            }
        }
        $(el + ' ' + itemsDiv).css('transform', 'translateX(' + -translateXval + 'px)');
    }

    //It is used to get some elements from btn
    function click(ell, ee) {
        var Parent = "#" + $(ee).parent().attr("id");
        var slide = $(Parent).attr("data-slide");
              ResCarousel(ell, Parent, slide);
    }

});
    </script>


 Step 5 :

Enjoy Folks

Thursday, August 29, 2019

How integrate angular model driven form in Sharepoint framework

Step1:

Welcome to model driven form,We need to import the ReactiveFormsModule from @angular/forms and use the same in the imports array. app.module.ts

Step2:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './Components/app.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, HttpClientModule, FormsModule, ReactiveFormsModule],
declarations: [ AppComponent ],
providers: [ ],
bootstrap: [ AppComponent ] ,
})
export class AppModule {}


Step3:

Angular Form Design


<form (ngSubmit)="onSubmit(regForm)" [formGroup]="regForm">
<div class="borderbtm">
<div class="row">
<div class="col-md-6 box-body">
<div class="form-group">
<div class="col-md-12">
<label> Start Date</label>
</div>
<div class="col-md-12">
<div class="input-group date datetimepicker">
<input type="text" formControlName="startdate" name="startdate" class="form-control"/>
<span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div>
</div>
</div>
</div>
<div class="col-md-6 box-body">
<div class="form-group">
<div class="col-md-12">
<label> End Date</label>
</div>
<div class="col-md-12">
<div class="input-group date datetimepicker">
<input type="text" formControlName="enddate" name="enddate" class="form-control" />
<span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div>
</div>
</div>
</div>
</div>
</div>
<div class="box-footer" style="text-align:center; padding-top: 20px;">
<button class="btn btn-default clear" style="padding-right: 20px;" type="cancel">CLEAR</button>
<button class="btn btn-primary" type="submit">SUBMIT</button>
</div>
</form>


step 4

App.component.ts design below

import { Component, Input, OnInit, Inject, ViewEncapsulation } from '@angular/core';
import {IWebPartContext} from '@microsoft/sp-webpart-base';
import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export interface ISPLists {
value: ISPList[];
}
export interface ISPList {
Title: string;
Id: string;
}
@Component({
moduleId: module.id, // this is the key
selector: 'my-spfx-app',
template: require("./app.component.html") as string
//templateUrl: './app.component.html'
//styleUrls : ['./app.component.css']
// styleUrls : ['./app.component.css']

//styles: ['./app.component.css']
})


export class AppComponent implements OnInit {

public name: string = '';
public context:IWebPartContext;
showGrid = true;
employeeitems :any;
regForm:FormGroup;
employeeleaveitems;

constructor(private formbuilder: FormBuilder){ }
public ngOnInit() {
this.setFormState();
this.getleavelist();
}
setFormState():void
{
this.regForm = this.formbuilder.group({
startdate : ['',[Validators.required]],
enddate : ['',[Validators.required]]
});
}
getleavelist()
{
this.context= window["webPartContext"];
this.name= this.context.pageContext.user.displayName;
this._getListData()
.then((response) => {
console.log(response);
this._renderList(response.value);
console.log(response.value);
});
}

onSubmit()
{
debugger;
let leaves = this.regForm.value;
console.log(leaves);
this.leavepost(leaves);
}

addleaves()
{
this.showGrid = false;
}

private _getListData(): Promise<ISPLists> {
debugger;
return this.context.spHttpClient.get(this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('SpfxLeave')/items", SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
debugger;
console.log(response);
return response.json();
});
}

private _renderList(items: ISPList[]): void {
this.employeeleaveitems =items;
}

leavepost(leaves:any) {



var itemType = "SP.Data.SpfxLeaveListItem";
var absoluteUri = this.context.pageContext.web.absoluteUrl;
const itemData: any = {
"__metadata": { "type": itemType },
'startdate':leaves.startdate,
'enddate': leaves.enddate,
'name': 'tentant name',
'leavetype': 'sick leave'
};
const itemHeader: any = {
'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': '',
"X-HTTP-Method": "POST"
};
const spHttpClientOptions: ISPHttpClientOptions = {
"headers": itemHeader,
"body": JSON.stringify(itemData)
};
this.context.spHttpClient.post(
absoluteUri + "/_api/web/lists/GetByTitle('SpfxLeave')/items",
SPHttpClient.configurations.v1,
spHttpClientOptions);

}
}


step5:

Here's my tsconfig.json :

Add the below line without fail.

"emitDecoratorMetadata": true,

Enjoy Folks

Wednesday, June 19, 2019

How to remove special characters and codes (using jQuery) from SharePoint rendered html?

Welcome to designers dairy, Here we are going to discuss,How to remove special characters and codes (using jQuery) from SharePoint rendered html
Step1:
It is a big headache, when you render the html  in share-point, There are lot of special characters especially  char code "#8203".
Step2:
To remove this special code include in html while rendering the page, we have to write a jquery script 

Script:
    $(document).ready(function()
{
jQuery('.OnboardingOnlinePortal-wrapper').each(function(index,element)  { 

       var exp = new RegExp(String.fromCharCode(8203),"g");
       var editor= jQuery(element);
       var txt = editor.html()
           txt = txt.replace(exp,'');
           txt = txt.replace(/&nbsp;/g,' ')
           txt = txt.replace(/ {2,}/g,' ');
       editor.html(txt);
  });
  return true;
 });

Step3:
In my scenario, I have included this script in the Page layout, based on your requirements, you can add in Pages or master pages.
To add the script in Page layout below is the placeholder 
  <script>//<![CDATA[
    $(document).ready(function()
{
jQuery('.OnboardingOnlinePortal-wrapper').each(function(index,element)  {

       var exp = new RegExp(String.fromCharCode(8203),"g");
       var editor= jQuery(element);
       var txt = editor.html()
           txt = txt.replace(exp,'');
           txt = txt.replace(/&nbsp;/g,' ')
           txt = txt.replace(/ {2,}/g,' ');
       editor.html(txt);
  });
  return true;
 });

//]]>
 </script>
Step3:

Thanks for reading the article.Stay Tuned on www.webdesignersdairy.com  for more updates on SharePoint.

Thursday, May 30, 2019

How to apply Custom Styles to Page Layouts in SharePoint

Welcome to  designer dairy blog, here we are going to  discuss How to apply Custom Styles to Page Layouts in

SharePoint


Step1:

We refer the css styles  in the masterpage, so that style applicable in all the pages. There may be situation comes , we want to override  the css file in the pages, which comes from masterpage.

Step2:

To override the styling in the particular page, best way to edit the page-layout of the particular page.

If you go "_Catlog/masterpage" You can find the pagelayouts in both .html and .aspx.

For example:

I have page called about.aspx, i want to change the style of the page. So i have to go pagelayouts and edit the aboutpagelayout.html file.


In your custom Page Layout, search for id=”PlaceHolderAdditionalPageHead“. You’ll find it in an opening tag that looks like this:


<!--MS:<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">-->
     <!--MS:<style type="text/css">--> 
          #wr_leftNav { display: none !important; } 
     <!--ME: </style>-->
So i have added the Inline-style above the contentplaceHolder, Based on your needs 
You can also add the Css reference link as below

<!--MS:<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">-->
 <link href="indigo_layout.css" rel="stylesheet" type="text/css" ms-design-css-conversion="no" />
Step3:

Step3:

Thanks for reading the article.Stay Tuned on www.webdesignersdairy.com  for more updates on Sharepoint.

Tuesday, May 28, 2019

Getting the id of the Input field value where the ID's are bind dynamically

Step1:

Welcome to designer dairy, here we are going to discuss how to get the id of the input field where the id gets bind dynamically on run time

Step2:

Let’s see how the jQuery.each() function helps us in conjunction with a jQuery object. The first example selects all the TD elements in the page and outputs their Id attribute.

<script>
$(document).ready(function()
{
$('td input').each(function(i)
{
  var id = $(this).attr('id');
  console.log(id);

});
});
</script>

Note:

$(this)  - >  iterate each item of the array.

If you use $('td input'), instead of $(this) you will be getting the first value not the second value.


Step3:

Entire Mark-up design

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('td input').each(function(i)
{
  var id = $(this).attr('id');
  console.log(id);

});
});
</script>

</head>
<body>

<table>
<tr>
<td>
<input type="checkbox" class="checkbox flat-red" id="UpcomingTaskMarkasComplete-244"
style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%;
height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
<td>
<td>
<input type="checkbox" class="checkbox flat-red" id="UpcomingTaskMarkasComplete-245"
style="position: absolute; opacity: 0;">
<ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%;
height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
<td>
</tr>
</body>
</html>

Thursday, May 16, 2019

Redirect parent window from an iframe action uisng Javascript

Welcome to  designer dairy blog, here we are going to  discuss how to Redirect parent window from an iframe action

Step1:

Example.html is the main page and  we are loading "example1.html" via an iframe tag.

Example.Html Mark-up

<html>
<head>
<body>
<iframe src="Example1.html"> </iframe>
</body>
</html>

Step2:

Example1.html  we have a button "Click Me", once the button is clicked, we have to redirect to url "www.google.com".

So we have to use window.top.location.href  to redirect parent window from an iframe action.

Html Mark-up - Example2.html

<script>
function changeurl()
{
window.top.location.href = "http://www.google.com";
}
</script>

<a href ="#"  id="accept" onclick="changeurl()"> Click Me </a>

Note: 

If your not using iframe tag, then u can use window.location.href to redirect parent window.

Step3:

Thanks for reading the article.Stay Tuned on www.webdesignersdairy.com  for more updates on Javascript.



Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...