Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Wednesday, March 8, 2017

Why Javascript works only after launching developer tool bar in IE once

Hi Friends,

This post basically talks about the strange experience which I faced in one of the applications.

Problem Statement:
In Internet Explorer, the Javascript/jQuery is not working until I open the IE Tool bar once.


Solution:
After multiple trial and errors, what I observed is, it's because of the console.log present in my jQuery file.

The console object will only be activated when the IE Dev Toolbar is opened. Prior to that, calling the console object will result as undefined. After the toolbar has been opened, the console will exist (even if the toolbar is subsequently closed), so your console calls will then work.


Hence make sure to remove any Console entries from the JS file during the roll-out of the application.


Hope this helps...

Wednesday, February 22, 2017

Open and Close a SharePoint modal dialog with HTML structure

HI Friends,

In this post we are going look at How to Open and Close a SharePoint Modal Dialog using HTML instead of webpage.

Generally we use SharePoint modal dialog in order to call a webpage as pop-in. But, in this post we are going to open a DIV as a pop-in using SharePoint modal dialogue SP.UI.ModalDialog.showModalDialog

Note: You can open any HTML structure as per your needs.

Please use the below code snippet which does this trick.

function OpenModaldialog() {
  SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    var element = document.createElement('div');
    element.innerHTML = '<div id="modalcontent">This is modal dialogue cocntent</div>';

    SP.UI.ModalDialog.showModalDialog({
     html: element,
     title: 'Dialogue box',
     allowMaximize: false,
     showClose: true,
     dialogReturnValueCallback : Function.createDelegate(null, CloseCallback),
     autoSize: true
    });
   }, "SP.js");
}

function CloseCallback(result, target) {
   //custom action if any
}

That's it, you just need to call the function OpenModaldialog(); on the onclick event of the button through which you want to launch the modal dialogue.

Hope this helps...

RELATED POST: How to Show and Hide a Modal Pop up Dialog in a SharePoint
RELATED POST: How to Open and Close a jquery dialog popup

Thursday, May 14, 2015

Add Asset picker(Browse and select file) control to Textbox in a Sharepoint list form Or Page

Hi Guys,

In this post we are going to learn How to add Asset picker control to a SharePoint FORM/Page.

Recently I came across a requirement where user needs to add the reference of a document present in a document library while adding a new list item. As Sharepoint doesn't provide you any OOTB column/field control to pick the asset from the site, User has to go the document library select the particular document then copy shortcut and finally paste the copied URL into List form.

Some of the users do not like this behavior when they have the file already present in document library and expects the option of browse and pick behavior.

In this post we will be adding the "browse and pick file" control to any Textbox box field(of List form) in which you wants to save the URL of the file.

Below are the steps which does the trick.

Step 1:
Create a js file called "createassetpickercontrol.js"

Step 2:
Add the following snippet to the "createassetpickercontrol.js"
$(document).ready(function () {

// With the below line we will be dynamically adding the Browse control next to the textbox where we need to place this. 

//Replace "controlid" with your actual id of the textbox.

$("textarea#controlid").closest('td').append("<div id='btnbrowsectrl' style='display:none'><input onclick='GetFileURL()' type='button' value='Browse File' /><span>Browse File location if exists on same site</span></div>");

 //The below snippet to acheive the browse functionality
//Create a object which will be used for the Asset. I have used the object name as 'assetPickerObj'
    with(new AssetPickerConfig('assetPickerObj'))
    {{
         DefaultAssetImageLocation='';
         //CurrentWebBaseUrl will be the url of the site or site collection.
         CurrentWebBaseUrl='https://siteurl.com';
         OverrideDialogFeatures='';
         OverrideDialogTitle='';
         OverrideDialogDesc='';
         OverrideDialogImageUrl='';
         //AssetUrlClientID is the id of the control in which the path of the selected file will be saved.
         AssetUrlClientID='controlid';
         AssetTextClientID='';                                                             
         UseImageAssetPicker=false; //make this false to show Documents instead
         DefaultToLastUsedLocation=true;
         DisplayLookInSection=true;                                                            
         ReturnCallback = null;}}
});

function GetFileURL(){
    //Following is the function which launch the AssetPortalBrowser.aspx automatically.
    APD_LaunchAssetPickerUseConfigCurrentUrl('assetPickerObj');

//the above line will just give you the relative url to the textbox.
//set absolute url in textbox if required then use the below lines
var newabsoluteurl= window.location.protocol + "//" + window.location.host+$("#controlid ").val().replace(/\s+/g,"%20");
$("#controlid").val(newabsoluteurl);

return false;

}

Step 3: 
Upload the above JS to your site.

Step 4:
Go to the List and then Select default New Form as shown below.

Add a HTML Form webpart and then add the below JS references in it and then Save the page.
AssetPicker.js is a sharepoint farm JS file and will be available in layouts folder. The folder structure will change from 2007 to 2010 environment.

<script src="/_layouts/1033/AssetPickers.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="/Style%20Library/Scripts/createassetpickercontrol.js" type="text/javascript"></script>

There you go, you could now see the browse button to pick the file url when you open the LIst form as below.

Hope this helps...

Open and Close a Sharepoint Modal Dialog with URL

Hi Folks, in my earlier post we have seen how to launch a popup in any page using purely jquery approach. Click here...
In this post we are going to acheive this with Sharepoint framework.

Sharepoint has exposed some client side functions where we can easily call a page as modal dialog/ pop up.

SP.UI.ModalDialog.showModalDialog(options) Method helps us in acheiving the same.

Below is the actual implementation of this function.

function openDialogAndReceiveData(tUrl, tTitle) {
         var options = {
             url: tUrl,
             title: tTitle,
    autoSize: false,
    width:600,
    height:350,
    dialogReturnValueCallback: onPopUpCloseCallBackWithData
         };
         SP.UI.ModalDialog.showModalDialog(options);
     }

function onPopUpCloseCallBackWithData(result, returnValue) {
//If any action that needs to be done on parent page upon close of popup.      
}

The above function is a generic one where we just need to call this function on the onclick of the button on which we are expecting the popin/modal dialog to be opened.
Parameters:
tUrl = absolute or relative path of the page which we need to see as a dialog
tTitle = Title of the modal dialog.

Hope this helps...

RELATED POST: Show and Hide a SharePoint modal dialog with HTML structure
RELATED POST: How to Show and Hide a jquery dialog popup

Monday, February 24, 2014

How to Show and Hide a jQuery UI dialog popup

In this post we are going to load a specific page in a jquery UI dialog box. Below are the steps which does the trick.
Step 1: 
Add the jquery reference and then
Add the below empty div to your HTML
<div id="dlgdivcontent">
</div> 

Step2: 
Add the below java script function to your page
var $mydialog;
    function opendialogbox(url, popintitle) {
        $mydialog= $('#dlgdivcontent')
               .html('<iframe " src="' + url + '" width="500" height="350" scrolling="auto" frameBorder="0"></iframe>')
               .dialog({
                   autoOpen: false,
                   show: "fade",
                   hide: "fade",
                   modal: true,
                   height: 350,
                   width: 500,
                   resizable: false,
                   title: popintitle,
                   close: function (event, ui) {
                   //custom action if any on close click
                   }


               });

        $mydialog.dialog('open');
    }

Step3: 
Call the function opendialogbox with parameters as Url and Title on which wherever the link/button that you want to trigger the dialog box.

Sunday, January 5, 2014

Update User Profile property through jQuery SPServices

Hi folks,
In this post we are going to update User Profile property through jQuery SPServices. Below is the code snippet which does the trick.
Just call the function with the parameters CurrentUserAccountName, PropertyName and PropertyValue.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>

function updateUserProfile(currUserAccName, propertyName, propertyValue) {
   var propertyData = "<PropertyData>" +
  "<IsPrivacyChanged>false</IsPrivacyChanged>" +
  "<IsValueChanged>true</IsValueChanged>" +
  "<Name>" + propertyName + "</Name>" +
  "<Privacy>NotSet</Privacy>" +
  "<Values><ValueData><Value xsi:type=\"xsd:string\">" + propertyValue + "</Value></ValueData></Values>" +
  "</PropertyData>";

   $().SPServices({
       operation: "ModifyUserPropertyByAccountName",
       async: false,
       webURL: "/",
       accountName: currUserAccName,
       newData: propertyData,
       completefunc: function (xData, Status) {
           var result = $(xData.responseXML);
           if (Status == "success") {
              //success message if needed
           }
       }
   });


}

Hope this helps...

Tuesday, September 24, 2013

jQuery spservices to get current user name for sharepoint site

Hi peeps,
In this post we are going to write a script which will give us the current user loggedin name for a sharepoint site using jQuery SPServices.
Below is the script:

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>
<script type="text/javascript">
var currentuserName = $().SPServices.SPGetCurrentUser({
   fieldName: "Title",
   debug: false
});
</script>


Hope this helps...
RELATED Post : How to display user information using ProfilePropertyLoader in sharepoint

JavaScript Back to Previous Page functionality on a button click

Hi Pals,
In this post we are going to see How to go back to previous page using Javascript on click of anchor button.

Below is the script which will take you to the previous page upon clicking on Back to previous page button.

<a href="#" onClick="history.go(-1)"> Back to Previous Page </a>

Wednesday, May 15, 2013

jQuery SPServices to get current user sharepoint groups

In this post we are going to get information of all the sharepoint user groups in which current user belongs using SPServices.

Below is the jQuery code snippet which will do this action.
In this example we will be looping all the groups which the current user is present and adding it to the variable  loggedinUserGroup.

// add the ref of jQuery file
<script type="text/javascript" src="/style library/jquery-1.7.2.js"></script>
// add the ref of jQuery SPServices file
<script type="text/javascript" src="/style library/jquery.SPServices-0.7.0.min.js"></script>
<script type="text/javascript">
var loggedinUserGroup;
$(document).ready(function() {
 Getrolesforuser();
 alert(loggedinUserGroup);
});
function Getrolesforuser()
{
 loggedinUserGroup="";
 $().SPServices({ 
  operation: "GetGroupCollectionFromUser", 
        userLoginName: $().SPServices.SPGetCurrentUser(), 
        async: false, 
        completefunc: function(xData, Status)
        {
         $(xData.responseXML).find("Group").each(function()
         {
              if(loggedinUserGroup=="")
              {
                  loggedinUserGroup = $(this).attr("Name");
              }
              else
              {
                  loggedinUserGroup = loggedinUserGroup + "\n"+ $(this).attr("Name");
              }
         });
               
  }
 });
}

</script>

Hope this helps... Follow this page for more updates.
Related post- jQuery spservices to get current user name for sharepoint site
Related post- How to display user information using ProfilePropertyLoader in sharepoint

Monday, March 18, 2013

Implementing Google chrome frame Plugin to your website


Google Chrome frame lets web developers create web features based on technologies that are not yet available in some versions of Internet Explorer, such as rich text editing and faster Javascript execution. If you use Internet Explorer, you can still use it to view websites that contain such features, by first downloading the Google Chrome Frame plugin.
This google chrome frame plugin is also used to avoid the memory leakage in IE if our site is using AJAX,jQuery. If once we have installed this plugin we just need to change the meta tag so that IE browser will render using chrome engine. Ref this link for more details.
In this Post we are going to Implement Google chrome frame Plugin to our website wherein we will be showing a div(ref figure below) on top of our page, only in Internet Explorer and if Google chrome frame Plugin is not installed.

Below are the steps:
Step1: Create a above div and place it at the top of the page. Make the div style as display:none

Step2: Checking google chrome frame plugin is installed on the machine or not.

Below is the function that can do the trick
function IsGoogleChromePluginInstalled() {
    try {
        var i = new ActiveXObject('ChromeTab.ChromeFrame');
        if (i) {
            return true;
        }
    }
    catch (e) {
    }
    return false;
}

Call the above function in the document.ready function. If the function above function returns false(means GCF plugin not installed) then make the above created div style as display:block. So that it will display the above div to the user.

Step3: Call the below function on the onclick= installGoogleChromeFrame(); for Install Now button

function installGoogleChromeFrame() {   
    if ($(".chromeFrameOverlayContent").length > 0) {
        $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").show();
    }
    else {
        CFInstall.check({
            url: document.location.protocol + "//" + {SingleUser Or Multi User url},
            mode: "overlay",
            destination: window.location
        });

        $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").show();
        var chromeframeheight = document.body.scrollHeight;
        $('.chromeFrameOverlayUnderlay').css('height', chromeframeheight);
        $("#chromeFrameCloseButton").click(function () {
            $(".chromeFrameOverlayContent, .chromeFrameOverlayUnderlay").css({ display: "none" });
        });

    }
}

Single user installation:

Multiple user installation:

Step4:
With the above three steps we are good to show a message to install the Google chrome frame Plugin.
When user clicks on Install Now button an overlay will comes up on top of our webpage asking user to install.

Hope this helps…


Saturday, February 23, 2013

Set this url as default/Home page of your browser


In this post we are going to set any url as default/Home page of your browser.
Recently one of my friend asked me to do this. So thought of sharing with you guys as well.
Consider we are going to set the http://www.google.co.in as the Default/Home page of the browser.

Add a below anchor tag to your webpage
<A style="CURSOR: hand; font-decoration: underline" href="#" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.google.co.in');">set as your home page</A>

So when user clicks on this button, a popin will appear asking to set google as the home page.
Just click on Ok. That's it, your browser has been updated with the default/Home page as google.com


Hope this helps...


Wednesday, December 5, 2012

Javascript to get query string value by passing the parameters siteUrl and querystringkey



In this post we will be writing a function to retrieve the query string value by passing the parameters siteUrl and querystringkey using Javascript.

Below is the function:
function getQuerystringForUrl(key,siteUrl) {   
    key = decodeURIComponent(key).replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);           
    var results = regex.exec(siteUrl);
    if (results == null)
        return;
    else
        return decodeURIComponent(results[1]);
}


Hope this helps...

Thursday, February 16, 2012

Javascript/jquery count li elements inside ul

Below is the script with which you can get the count of li present in ul..


Html::

<ul id="myulid">
  <li>List Item1</li>
  <li>List Item2</li>
  <li>List Item3</li>
  <li>List Item4</li>
  <li>List Item5</li>
</ul>

Java Script:: 


<script type="text/javascript">
var myul = document.getElementById('myulid');
var liCount= myul.getElementsByTagName('li').length;
alert(liCount);
</script>


Hope this helps...

Popular Posts