<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>javascript &#8211; Kodono</title>
	<atom:link href="https://blog.kodono.info/wordpress/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.kodono.info/wordpress</link>
	<description>Pour tous les technophiles</description>
	<lastBuildDate>Thu, 08 Dec 2022 19:08:02 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.1</generator>
	<item>
		<title>Capacitor Plugin for HTTP requests with self-signed SSL certificates</title>
		<link>https://blog.kodono.info/wordpress/2021/10/30/capacitor-plugin-for-http-requests-with-self-signed-ssl-certificates/</link>
					<comments>https://blog.kodono.info/wordpress/2021/10/30/capacitor-plugin-for-http-requests-with-self-signed-ssl-certificates/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Sat, 30 Oct 2021 13:26:01 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Astuce]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau expert]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=2094</guid>

					<description><![CDATA[I&#8217;m using CapacitorJS for easy development with Android. I needed a way to do an HTTPS request to a box that uses self-signed SSL certificate. To accomplish it, I created my own capacitor plugin. See this wiki page for details: https://github.com/Aymkdn/assistant-freebox-cloud/wiki/Capacitor-Plugin-for-HTTP-requests-with-self-signed-SSL-certificates]]></description>
										<content:encoded><![CDATA[<p>I&#8217;m using CapacitorJS for easy development with Android. I needed a way to do an HTTPS request to a box that uses self-signed SSL certificate. To accomplish it, I created my own capacitor plugin.</p>
<p>See this wiki page for details: <a href="https://github.com/Aymkdn/assistant-freebox-cloud/wiki/Capacitor-Plugin-for-HTTP-requests-with-self-signed-SSL-certificates">https://github.com/Aymkdn/assistant-freebox-cloud/wiki/Capacitor-Plugin-for-HTTP-requests-with-self-signed-SSL-certificates</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2021/10/30/capacitor-plugin-for-http-requests-with-self-signed-ssl-certificates/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>SP.Utilities.Utility.SendEmail returns &#8220;The e-mail message cannot be sent. Make sure the e-mail has a valid recipient.&#8221;</title>
		<link>https://blog.kodono.info/wordpress/2019/06/28/sp-utilities-utility-sendemail-returns-the-e-mail-message-cannot-be-sent-make-sure-the-e-mail-has-a-valid-recipient/</link>
					<comments>https://blog.kodono.info/wordpress/2019/06/28/sp-utilities-utility-sendemail-returns-the-e-mail-message-cannot-be-sent-make-sure-the-e-mail-has-a-valid-recipient/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Fri, 28 Jun 2019 14:01:58 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1967</guid>

					<description><![CDATA[With Sharepoint you can use SP.Utilities.Utility.SendEmail to send email in JavaScript, however you could receive the below error: &#8220;The e-mail message cannot be sent. Make sure the e-mail has a valid recipient.&#8221; After searching the web, I found the solution: instead of using an email address for the recipients you have to use the userDomain [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>With Sharepoint you can use <a href="https://gist.github.com/BasantPandey/05189832546f2c6cc0bd008fcfec3264">SP.Utilities.Utility.SendEmail</a> to send email in JavaScript, however you could receive the below error:</p>
<blockquote><p>
&#8220;The e-mail message cannot be sent. Make sure the e-mail has a valid recipient.&#8221;
</p></blockquote>
<p>After searching the web, I found <a href="http://sadomovalex.blogspot.com/2015/08/one-of-reasons-of-why-sending-email-via.html">the solution</a>: <b>instead of using an email address for the recipients</b> you have to use the <b>userDomain with &#8220;i:0#.w|&#8221;</b>.</p>
<p>For example, if the user is John Doe, and his email is john_doe@company.com, then you should use something like <b>i:0#.w|domain\\john_doe</b>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2019/06/28/sp-utilities-utility-sendemail-returns-the-e-mail-message-cannot-be-sent-make-sure-the-e-mail-has-a-valid-recipient/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Remove custom properties/metadata for an Office document [javascript]</title>
		<link>https://blog.kodono.info/wordpress/2018/04/19/remove-custom-properties-metadata-for-an-office-document-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2018/04/19/remove-custom-properties-metadata-for-an-office-document-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 19 Apr 2018 17:13:30 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau expert]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1891</guid>

					<description><![CDATA[I have this document library on Sharepoint where I have one custom column called Metadata and that is a lookup to another list on my Sharepoint. When the users download an Office document from this library and then re-upload it we could have the below error message: There is at least one lookup column that [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I have this document library on Sharepoint where I have one custom column called <em>Metadata</em> and that is a lookup to another list on my Sharepoint.</p>
<p>When the users download an Office document from this library and then re-upload it we could have the below error message:</p>
<blockquote><p>There is at least one lookup column that enforces a relationship behavior and contains values that reference one or more non-existent items in the target list.</p></blockquote>
<p>It&#8217;s because the Office documents keep the custom columns from the document library from where they have been downloaded&#8230; In that case the file tries to reassign the <em>Metadata</em> with an ID that doesn&#8217;t exist anymore&#8230; causing this issue!</p>
<p>Because I&#8217;m using a homemade interface to upload documents, I&#8217;ve been able to pass some code to delete the file&#8217;s properties on-the-fly before pushing it into the document library.</p>
<p>To do so, you need <a href="https://stuk.github.io/jszip/">JSZip</a> that will permit to unzip the Office document in order to retrieve the file <b>docProps/custom.xml</b> and to change the properties we want before the final upload.</p>
<p>Let&#8217;s imagine my page contains an <code>&lt;input type="file"&gt;</code>, and that I have already loaded JSZip. Then I use <a href="https://developer.mozilla.org/fr/docs/Web/API/FileReader/readAsArrayBuffer">FileReader</a>:</p>
<pre class="brush:javascript">
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  // content is the "arraybuffer" that represents my file
  var content = e.target.result;
  // check the file's extension (here "docx", "xlsx", and "pptx", but we could add more extensions
  var ext=file.name.split(".").slice(-1)[0];
  switch (ext) {
    case "docx":
    case "xlsx":
    case "pptx": {
      // load content in JSZip
      JSZip.loadAsync(content)
      .then(function(zip) {
        // unzip the file that contains metadata/properties
        return zip.file("docProps/custom.xml").async("text")
        .then(function(txt) {
          // replace the faulty column
          txt = txt.replace(/name="Metadata">&lt;vt:lpwstr>\d+&lt;\/vt:lpwstr>/,'name="Metadata">&lt;vt:lpwstr>&lt;\/vt:lpwstr>');
          // reinject the new file
          zip.file("docProps/custom.xml", txt);
          return zip.generateAsync({type:"arraybuffer"})
        })
      })
      .then(function(content) {
        // do something with your content
        // for example (https://aymkdn.github.io/SharepointPlus/): $SP().list("my_list").createFile({content:content, filename:file.name})
      })
      break;
    }
    default: {
      // for the other files, treat them normally
      // for example (https://aymkdn.github.io/SharepointPlus/): $SP().list("my_list").createFile({content:content, filename:file.name})
    }
  }
}
fileReader.onerror = function(e) {
  console.error(e.target.error);
}
fileReader.readAsArrayBuffer(file);
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2018/04/19/remove-custom-properties-metadata-for-an-office-document-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to delete a document locked by another user in Sharepoint using JavaScript</title>
		<link>https://blog.kodono.info/wordpress/2017/11/20/how-to-delete-a-document-locked-by-another-user-in-sharepoint-using-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2017/11/20/how-to-delete-a-document-locked-by-another-user-in-sharepoint-using-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 20 Nov 2017 10:37:03 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau expert]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1862</guid>

					<description><![CDATA[When you open a file from Sharepoint, it will receive a short term lock that will prevent others to change some properties on the file. This protection can be useful, but also very annoying, for example when the file is not closed properly, then the lock could stay &#8220;forever&#8221;. There are many posts on the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>When you open a file from Sharepoint, it will receive a short term lock that will prevent others to change some properties on the file.</p>
<p>This protection can be useful, but also very annoying, for example when the file is not closed properly, then the lock could stay &#8220;forever&#8221;.</p>
<p>There are <a href="https://sharepoint.stackexchange.com/questions/42999/clearing-short-term-file-lock">many</a> <a href="https://sharepoint.stackexchange.com/questions/120246/how-to-delete-a-document-locked-by-another-user-im-a-super-admin">posts</a> <a href="https://sharepoint.stackexchange.com/questions/165970/can-we-unlock-a-shortterm-lock-via-csom-for-sp2013">on</a> <a href="https://sharepoint.stackexchange.com/questions/202665/the-file-is-locked-for-exclusive-use-by-same-person-sharepoint-online">the web</a> about it.</p>
<p>I found one that has been super useful: <a href="https://pholpar.wordpress.com/2014/04/07/how-to-use-javascript-to-delete-short-term-locks-from-documents-opened-from-sharepoint/">https://pholpar.wordpress.com/2014/04/07/how-to-use-javascript-to-delete-short-term-locks-from-documents-opened-from-sharepoint/</a><br />
The author explains very well the different steps what I&#8217;m trying to summarize:</p>
<ol>
<li>Send a request to <code>_vti_bin/_vti_aut/author.dll</code> with special headers/body</li>
<li>Auth.dll will provide the <code>lockid</code></li>
<li>Send a request to <code>_vti_bin/cellstorage.svc/CellStorageService</code> with special headers/body, included the <code>lockid</code></li>
<li>The file is unlocked</li>
</ol>
<p>The code to send to CellStorageService, and provided by the author, didn&#8217;t work for me. I&#8217;ve had to use Fiddler and open the document into Office on my computer to see the kind of requests send by it to unlock a document. Based on it, I&#8217;ve re-built the code and you can find my solution below.</p>
<p>Tested on Sharepoint 2013 On-Promise only. I don&#8217;t know if this solution works for Sharepoint Online or other version.<br />
Also note that I use <code>$SP().ajax()</code> from <a href="https://aymkdn.github.io/SharepointPlus/">SharepointPlus</a>, but it&#8217;s equivalent to the <code>$.ajax</code> from jQuery.</p>
<pre class="brush:javascript">
// full path to the document
var docUrl = "https://website.com/website/Doc_Library/Test.docx";

// start by querying author.dll to find the lockid and the user who locked it
$SP().ajax({
  url: 'https://website.com/website/_vti_bin/_vti_aut/author.dll',
  headers:{
    "Content-Type": "application/x-www-form-urlencoded",
    "MIME-Version": "1.0",
    "Accept": "auth/sicily",
    "X-Vermeer-Content-Type": "application/x-www-form-urlencoded"
  },
  body: 'method=getDocsMetaInfo%3a14%2e0%2e0%2e6009&#038;url%5flist=%5b' + encodeURIComponent(docUrl) + '%5d&#038;listHiddenDocs=false&#038;listLinkInfo=false',
}).then(function(source) {
  // go thru the source page returned to find the lockid and current user
  var nextLine = false;
  var ret = { "lockid":"", "user":"", when:"" };
  source.split("\n").forEach(function(line) {
    if (line.indexOf("vti_sourcecontrollockid") !== -1) nextLine="lockid"; // vti_sourcecontrollockid -> the lockid to use later
    else if (line.indexOf("vti_sourcecontrolcheckedoutby") !== -1) nextLine="user"; // vti_sourcecontrolcheckedoutby -> username of the user who locked it
    else if (line.indexOf("vti_sourcecontrollockexpires") !== -1) nextLine="when"; // vti_sourcecontrollockexpires -> when the server is supposed to unlock it
    else if (nextLine !== false) {
      ret[nextLine] = line.slice(7).replace(/&#([0-9]|[1-9][0-9]|[[01][0-9][0-9]|2[0-4][0-9]|25[0-5]);/g, function (str, match) { return  String.fromCharCode(match); });
      nextLine = false;
    }
  });

  if (!ret.lockid) { alert("Not Locked") }
  else {
    // compose a request based on what Microsoft Office sends to the Sharepoint server
    // found using Fiddler
    var releaseLockReq = '&lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">&lt;s:Body>&lt;RequestVersion Version="2" MinorVersion="2" xmlns="http://schemas.microsoft.com/sharepoint/soap/"/>&lt;RequestCollection CorrelationId="{96A244BD-D13B-4696-9355-231FB673BC4F}" xmlns="http://schemas.microsoft.com/sharepoint/soap/">&lt;Request Url="'+docUrl+'" UseResourceID="true" UserAgent="{1984108C-4B93-4EEB-B320-919432D6E593}" UserAgentClient="msword" UserAgentPlatform="win" Build="16.0.8201.2102" MetaData="1031" RequestToken="1">&lt;SubRequest Type="ExclusiveLock" SubRequestToken="1">&lt;SubRequestData ExclusiveLockRequestType="ReleaseLock" ExclusiveLockID="'+ret.lockid+'"/>&lt;/SubRequest>&lt;/Request>&lt;/RequestCollection>&lt;/s:Body>&lt;/s:Envelope>';

    // we send it to the webservice cellstorage.svc
    $SP().ajax({
      url:'https://website.com/website/_vti_bin/cellstorage.svc/CellStorageService',
      body:releaseLockReq,
      headers:{
        'Content-Type':'text/xml; charset=UTF-8',
        'SOAPAction': "http://schemas.microsoft.com/sharepoint/soap/ICellStorages/ExecuteCellStorageRequest"
      }
    })
    .then(function(res) {
      if (res.indexOf('ErrorCode="Success"') !== -1) alert("Success") // the file has been unlocked
      else alert("Failed")
    })
  }
})
</pre>
<p>I hope it will be useful to someone else!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/11/20/how-to-delete-a-document-locked-by-another-user-in-sharepoint-using-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Overwrite the Created field for a Sharepoint list item</title>
		<link>https://blog.kodono.info/wordpress/2017/08/28/overwrite-the-created-field-for-a-sharepoint-list-item/</link>
					<comments>https://blog.kodono.info/wordpress/2017/08/28/overwrite-the-created-field-for-a-sharepoint-list-item/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 28 Aug 2017 13:42:04 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1852</guid>

					<description><![CDATA[Sharepoint provides automatic fields, like &#8220;Created&#8221; that contains the creation date of a list item. It&#8217;s a readonly field. You could use a webservice to change the ReadOnly property in order to overwrite its value. Using SharepointPlus the code is: // don't change the below information // the details about this field are found using [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Sharepoint provides automatic fields, like &#8220;Created&#8221; that contains the creation date of a list item. It&#8217;s a readonly field.</p>
<p>You could use a webservice to change the <code>ReadOnly</code> property in order to overwrite its value.</p>
<p>Using <a href="http://aymkdn.github.io/SharepointPlus/">SharepointPlus</a> the code is:</p>
<pre class="brush:javascript">
// don't change the below information
// the details about this field are found using $SP().list().info
var updateSystemFields = "<Fields>" +
    '<Method ID="1">' +
    '<Field ID="{8c06beca-0777-48f7-91c7-6da68bc07b69}" Name="Created" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Created" Group="_Hidden" ColName="tp_Created" RowOrdinal="0" ReadOnly="FALSE" Type="DateTime" DisplayName="Created" StorageTZ="TRUE">' +
    "</Field></Method>" +
    "</Fields>";
// send the request to the server
$SP().webService({
  webURL: "https://website.url.com/",
  service: "Lists",
  operation:"UpdateList",
  properties:{
    listName: "Name of the list",
    listProperties: "",
    updateFields: updateSystemFields,
    newFields: "",
    deleteFields: "",
    listVersion: "",
  }
})
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/08/28/overwrite-the-created-field-for-a-sharepoint-list-item/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Change a &#8220;Choice with Fill-In&#8221; field into a magic dropdown [Sharepoint]</title>
		<link>https://blog.kodono.info/wordpress/2017/07/19/change-a-choice-with-fill-in-field-into-a-magic-dropdown-sharepoint/</link>
					<comments>https://blog.kodono.info/wordpress/2017/07/19/change-a-choice-with-fill-in-field-into-a-magic-dropdown-sharepoint/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 19 Jul 2017 15:45:48 +0000</pubDate>
				<category><![CDATA[Astuce]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1826</guid>

					<description><![CDATA[Sometimes you want to modify the options for a dropdown box by removing some existing options, however you want to be able to keep these old values for reporting or whatever reasons. Below is a way to do it by using jQuery and SharepointPlus. It will hide the &#8220;Specify your own value&#8221; stuff, and add [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Sometimes you want to modify the options for a dropdown box by removing some existing options, however you want to be able to keep these old values for reporting or whatever reasons.</p>
<p>Below is a way to do it by using jQuery and <a href="https://aymkdn.github.io/SharepointPlus/">SharepointPlus</a>. It will hide the &#8220;Specify your own value&#8221; stuff, and add the old value (if any) into the dropdown selection.</p>
<p>For example if you have a Choice field with options &#8220;A&#8221;, &#8220;B&#8221;, &#8220;C&#8221;. Your item ID #1 has value &#8220;B&#8221;.<br />
After a while you decide to delete &#8220;B&#8221; and add &#8220;D&#8221;, but you want to be able to find items with the &#8220;B&#8221; value.<br />
So you choose &#8220;Choice with Fill-In&#8221; and apply the below code:</p>
<pre class="brush:javascript">
// For flexibility reasons we create them as a Choice with Fill-In option,
//    however we hide the free text field and we show only the dropdown
//    in case of the fill-in has a value, then we add it into the list of options
$SP().formfields(["My Fist Dropdown", "Another One"]).each(function() {
  var $e = this.elem();
  // hide all except the dropdown
  //$e.not('select').hide().filter(':radio:last').closest('tr').hide(); // SP2010
  $e.eq(0).closest('table').find('tr:gt(0)').hide(); // SP2013
  // if we have a value into the fill-in box, then:
  //   - add it into the options
  //   - when another value is selected we check the first checkbox
  var fillValue = $e.last().val();
  if (fillValue) {
    $e.filter('select').append('&lt;option data-fillin="true">'+fillValue+'&lt;/option>').each(function() {
      var $this=$(this);
      $this.find('option:last').prop("selected", true);
      $this.removeAttr("onclick").on('change', function(event) {
        var $opt = $(this).find(':selected');
        if ($opt.data("fillin")) {
          $e.filter(':radio:last').prop("checked", true);
        } else {
          $e.filter(':radio:first').prop("checked", true);
        }
      });
    });
  }
})
</pre>
<p>So now, if you create a new item you&#8217;ll see a dropdown with &#8220;A&#8221;, &#8220;C&#8221;, and &#8220;D&#8221; only.<br />
But if you edit your item #1, you&#8217;ll have a dropdown with &#8220;A&#8221;, &#8220;C&#8221;, &#8220;D&#8221; and &#8220;B&#8221;.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/07/19/change-a-choice-with-fill-in-field-into-a-magic-dropdown-sharepoint/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Trigger an event when a file is uploaded on Sharepoint 2013 by drag and drop</title>
		<link>https://blog.kodono.info/wordpress/2017/06/23/trigger-an-event-when-a-file-is-uploaded-on-sharepoint-2013-by-drag-and-drop/</link>
					<comments>https://blog.kodono.info/wordpress/2017/06/23/trigger-an-event-when-a-file-is-uploaded-on-sharepoint-2013-by-drag-and-drop/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Fri, 23 Jun 2017 10:32:08 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1817</guid>

					<description><![CDATA[If you want to trigger an event after a drag&#038;drop a file for an upload operation on Sharepoint, then you&#8217;ll have to add some JavaScript into your page. // we need to make sure sp.core.js is loaded SP.SOD.executeOrDelayUntilScriptLoaded(function() { window.UploadFinishFunc=function(b, a) { typeof g_currentControl.postUploadFunc == "function" &#038;&#038; a.status != UploadStatus.CANCELLED &#038;&#038; g_currentControl.postUploadFunc(a.files); a.status != UploadStatus.CANCELLED [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>If you want to trigger an event after a drag&#038;drop a file for an upload operation on Sharepoint, then you&#8217;ll have to add some JavaScript into your page.</p>
<pre class="brush:javascript">
// we need to make sure sp.core.js is loaded
SP.SOD.executeOrDelayUntilScriptLoaded(function() {
  window.UploadFinishFunc=function(b, a) {
    typeof g_currentControl.postUploadFunc == "function" &#038;& a.status != UploadStatus.CANCELLED &#038;& g_currentControl.postUploadFunc(a.files);
    a.status != UploadStatus.CANCELLED &#038;& myPostUploadFunc(a);
    g_currentControl.status = ControlStatus.UPLOADED;
    UpdateProgressBar(ProgressMessage.UPLOADED, a);
    RefreshResult(a);
    g_currentControl.status = ControlStatus.IDLE
  }
}, 'sp.core.js');
SP.SOD.executeFunc('sp.core.js')

// below is the function that will be called
function myPostUploadFunc(data) {
  console.log("myPostUploadFunc => ",data)
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/06/23/trigger-an-event-when-a-file-is-uploaded-on-sharepoint-2013-by-drag-and-drop/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Adding a custom action to a callout in SharePoint 2013</title>
		<link>https://blog.kodono.info/wordpress/2017/06/21/adding-a-custom-action-to-a-callout-in-sharepoint-2013/</link>
					<comments>https://blog.kodono.info/wordpress/2017/06/21/adding-a-custom-action-to-a-callout-in-sharepoint-2013/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 21 Jun 2017 15:15:03 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[Astuce]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1814</guid>

					<description><![CDATA[This article has been VERY useful. But I wanted something lightly different: I wanted to add a custom action, but also have the &#8220;EDIT&#8221; button (but not the &#8220;SHARE&#8221;), and to use the current item info for my custom action. Here is the result: // source: https://www.eliostruyf.com/adding-a-custom-action-to-a-callout-in-sharepoint-2013/ // add a special callout action for our [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>This <a href="https://www.eliostruyf.com/adding-a-custom-action-to-a-callout-in-sharepoint-2013/">article</a> has been VERY useful. But I wanted something lightly different: I wanted to add a custom action, but also have the &#8220;EDIT&#8221; button (but not the &#8220;SHARE&#8221;), and to use the current item info for my custom action.</p>
<p>Here is the result:</p>
<pre class="brush:javascript">
// source: https://www.eliostruyf.com/adding-a-custom-action-to-a-callout-in-sharepoint-2013/
// add a special callout action for our library
SP.SOD.executeFunc("callout.js", "Callout", function () {
  var itemCtx = {};
  itemCtx.Templates = {};
  itemCtx.BaseViewID = 'Callout';
  // Define the list template type
  itemCtx.ListTemplateType = 101;
  itemCtx.Templates.Footer = function (itemCtx) {
    // context, custom action function, show the ECB menu (boolean)
    return CalloutRenderFooterTemplate(itemCtx, AddCustomAction, true);
  };
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx);
});

function AddCustomAction (renderCtx, calloutActionMenu) {
  var itemIndex = renderCtx.CurrentItemIdx
  // Add your custom action
  calloutActionMenu.addAction(new CalloutAction ({
    text: "Custom Action",
    tooltip: 'This is your custom action',
    onClickCallback: function() {
      // all the data related to your item are into `renderCtx.ListData.Row[itemIndex]`
      console.log('Callback from custom action');
    }
  }));
  // re-add EDIT action
  calloutActionMenu.addAction(new CalloutAction ({
    text: "Edit",
    onClickCallback: function(event) {
      // use the default action we have when clicking on the filename into the library
      // or call the EditForm if it's a list item and not a library
      DispEx(this, event,'TRUE','FALSE','FALSE','SharePoint.OpenDocuments.3','1','SharePoint.OpenDocuments','','1https://your.sharepoint.com/_layouts/15/WopiFrame.aspx?sourcedoc='+renderCtx.ListData.Row[itemIndex].FileRef+'&#038;action=default','','1','0','0','0x7fffffffffffffff')
    }
  }));
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/06/21/adding-a-custom-action-to-a-callout-in-sharepoint-2013/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sharepoint Callout Documentation</title>
		<link>https://blog.kodono.info/wordpress/2017/06/19/sharepoint-callout-documentation/</link>
					<comments>https://blog.kodono.info/wordpress/2017/06/19/sharepoint-callout-documentation/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 19 Jun 2017 14:47:40 +0000</pubDate>
				<category><![CDATA[À bookmarker]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1812</guid>

					<description><![CDATA[It&#8217;s difficult to find the JavaScript documentation for the Sharepoint Callout popup&#8230; So there is the link for a quick reference: https://msdn.microsoft.com/en-us/library/office/dn135236%28v=office.15%29.aspx]]></description>
										<content:encoded><![CDATA[<p>It&#8217;s difficult to find the JavaScript documentation for the Sharepoint Callout popup&#8230; So there is the link for a quick reference: <a href="https://msdn.microsoft.com/en-us/library/office/dn135236%28v=office.15%29.aspx">https://msdn.microsoft.com/en-us/library/office/dn135236%28v=office.15%29.aspx</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/06/19/sharepoint-callout-documentation/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sharepoint CallOut Popup</title>
		<link>https://blog.kodono.info/wordpress/2017/06/14/sharepoint-callout-popup/</link>
					<comments>https://blog.kodono.info/wordpress/2017/06/14/sharepoint-callout-popup/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 14 Jun 2017 15:46:29 +0000</pubDate>
				<category><![CDATA[À bookmarker]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1805</guid>

					<description><![CDATA[You can find the documentation of the cool Sharepoint CallOut Popup on dev.office.com: https://dev.office.com/sharepoint/docs/sp-add-ins/highlight-content-and-enhance-the-functionality-of-sharepoint-hosted-sharepoint]]></description>
										<content:encoded><![CDATA[<p>You can find the documentation of the cool Sharepoint CallOut Popup on dev.office.com: <a href="https://dev.office.com/sharepoint/docs/sp-add-ins/highlight-content-and-enhance-the-functionality-of-sharepoint-hosted-sharepoint">https://dev.office.com/sharepoint/docs/sp-add-ins/highlight-content-and-enhance-the-functionality-of-sharepoint-hosted-sharepoint</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/06/14/sharepoint-callout-popup/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Trigger an event when an element is visible in a scrollable area [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2017/05/03/trigger-an-event-when-an-element-is-visible-in-a-scrollable-area-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2017/05/03/trigger-an-event-when-an-element-is-visible-in-a-scrollable-area-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 03 May 2017 09:31:21 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1786</guid>

					<description><![CDATA[EDIT in 2022 It might also be interesting to look at Intersection Observer that is now available in most browsers, and there is also a polyfill. const observer = new IntersectionObserver((entries, observer) => { entries.forEach((entry) => { let isVisible=(entry.intersectionRatio===1); }); }, {threshold:1}); observer.observe(document.querySelector('#element'); END EDIT I have this specific need that is to trigger an [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><strong>EDIT in 2022</strong></p>
<p>It might also be interesting to look at <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer</a> that is now available in most browsers, and there is also a <a href="https://github.com/WICG/IntersectionObserver">polyfill</a>.</p>
<pre class="brush:javascript">
const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    let isVisible=(entry.intersectionRatio===1);
  });
}, {threshold:1});
observer.observe(document.querySelector('#element');
</pre>
<p><strong>END EDIT</strong></p>
<p>I have this specific need that is to trigger an event when an element becomes visible/invisible into a scrollable area. Here is the code I came to:</p>
<pre class="brush:javascript">
/**
 * Create the handler
 * @param {NodeElement} holder The scrollable area to monitor (where the 'scroll' event will be apply)
 */
var VisibleEventListener = function(holder) {
  var _this=this;
  _this.started = false;
  _this.holder = holder;
  // detect if an element is visible
  _this.isScrolledIntoView=function(el) {
    var bndElem = el.getBoundingClientRect();
    var bndHolder = _this.holder.getBoundingClientRect();
    return bndElem.top &lt;= bndHolder.top ? !(bndHolder.top - bndElem.top > bndElem.height) : !(bndElem.bottom - bndHolder.bottom > bndElem.height);
  }
  // permits to deal with the scroll
  _this.scrollHandler=function(e) {
    for (var i=0, len=_this.events.length; i&lt;len; i++) {
      _this.events[i].check();
    }
  }
  _this.events=[];
}
/**
 * Add the visible/invisible event for an element into a scrollable area
 * @param {NodeElement}   element  The element to test
 * @param {String}   listener 'visible' or 'invisible'
 * @param {Function} callback The callback function to be called when the event is triggered
 */
VisibleEventListener.prototype.add = function(element, listener, callback) {
  var _this=this;
  var ElementToMonitor=function(element, listener, callback) {
    this._super=_this;
    this.element=element;
    this.isVisible=false;
    this.callback=callback;
    this.listener=listener;
  }
  ElementToMonitor.prototype.check = function() {
    var visible=this._super.isScrolledIntoView(this.element);
    if (visible &#038;& !this.isVisible) { // becomes visible
      this.isVisible=true;
      if (this.listener==='visible') this.callback.call(this.element)
    } else if (!visible &#038;& this.isVisible) { // becomes invisible
      this.isVisible=false;
      if (this.listener==='invisible') this.callback.call(this.element)
    }
  };
  var etm=new ElementToMonitor(element,listener,callback);
  _this.events.push(etm);
  // if we have started to monitor
  if (_this.started===true) etm.check();
}
VisibleEventListener.prototype.start = function() {
  this.holder.addEventListener('scroll', this.scrollHandler);
  this.started = true;
  // trigger the check to verify if the elements are already visible
  this.scrollHandler();
}
VisibleEventListener.prototype.stop = function() {
  this.holder.removeEventListener('scroll', this.scrollHandler);
  this.started = false;
}
</pre>
<p>And to use it:</p>
<pre class="brush:javascript">
// initiate our area with VisibleEventListener
var vel = new VisibleEventListener(document.querySelector('#s4-workspace'));
// add the elements to monitor
vel.add(document.querySelector('.slideshow'), 'invisible', function() {
  console.log(this,' is now invisible')
})
vel.add(document.querySelector('.slideshow'), 'visible', function() {
  console.log(this,' is now visible')
})
// start the monitoring
vel.start();
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/05/03/trigger-an-event-when-an-element-is-visible-in-a-scrollable-area-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Check if an element is visible [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2017/05/03/check-if-an-element-is-visible-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2017/05/03/check-if-an-element-is-visible-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 03 May 2017 08:14:02 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1784</guid>

					<description><![CDATA[We can find plenty of answers about how to check if an element is visible. In my case the one which works with opacity, and into a scrollable area, is this one (that I have optimized): function isScrolledIntoView(el, holder) { var bndElem = el.getBoundingClientRect(); var bndHolder = holder.getBoundingClientRect(); return bndElem.top &#60;= bndHolder.top ? !(bndHolder.top - [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>We can find plenty of answers about how to check if an element is visible.</p>
<p>In my case the one which works with <code>opacity</code>, and into a scrollable area, is <a href="http://stackoverflow.com/a/41754707/1134119">this one</a> (that I have optimized):</p>
<pre class="brush:javascript">
function isScrolledIntoView(el, holder) {
  var bndElem = el.getBoundingClientRect();
  var bndHolder = holder.getBoundingClientRect();
  return bndElem.top &lt;= bndHolder.top ? !(bndHolder.top - bndElem.top > bndElem.height) : !(bndElem.bottom - bndHolder.bottom > bndElem.height);
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/05/03/check-if-an-element-is-visible-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Resolve Promise one after another, in sequence</title>
		<link>https://blog.kodono.info/wordpress/2017/04/13/resolve-promise-one-after-another-in-sequence/</link>
					<comments>https://blog.kodono.info/wordpress/2017/04/13/resolve-promise-one-after-another-in-sequence/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 13 Apr 2017 15:30:02 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1779</guid>

					<description><![CDATA[Below is the code that is handy when you want to execute several Promise actions in sequence: function PromiseChain(arr, fct) { var dfd = Promise.resolve(); var res = arr.map(function(item,idx) { dfd = dfd.then(function() { return fct(item,idx) }); return dfd }); return Promise.all(res) } // for short version: // function PromiseChain(n,r){var e=Promise.resolve(),i=n.map(function(n,i){return e=e.then(function(){return r(n,i)})});return Promise.all(i)} And [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Below is the code that is handy when you want to execute several Promise actions in sequence:</p>
<pre class="brush:javascript">
function PromiseChain(arr, fct) {
  var dfd = Promise.resolve();
  var res = arr.map(function(item,idx) {
    dfd = dfd.then(function() {
      return fct(item,idx)
    });
    return dfd
  });
  return Promise.all(res)
}

// for short version:
// function PromiseChain(n,r){var e=Promise.resolve(),i=n.map(function(n,i){return e=e.then(function(){return r(n,i)})});return Promise.all(i)}
</pre>
<p>And an example about how to use it:</p>
<pre class="brush:javascript">
function promFunc(key) {
  return new Promise(function(prom_res) {
    setTimeout(function() { prom_res(key) }, 1000);
  })
}

PromiseChain(["a", "b", "c"], function(val, idx) {
  console.log(idx, val);
  return promFunc(idx+"_"+val);
})
.then(function(res) {
  console.log(res);
})

// result:
// 0 a
// 1 b
// 2 c
// Array [ "0_a", "1_b", "2_c" ]
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/04/13/resolve-promise-one-after-another-in-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Deep clone an object in JavaScript</title>
		<link>https://blog.kodono.info/wordpress/2017/04/12/deep-clone-an-object-in-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2017/04/12/deep-clone-an-object-in-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 12 Apr 2017 10:52:12 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1776</guid>

					<description><![CDATA[We can find many discussions and solutions about this issue. In my case the one that worked is this code. Below you&#8217;ll find a compressed version of the extend() function (with a fix): function extend(){var r,t,n,o,e=arguments[0]&#124;&#124;{},f=1,i=arguments.length,u=!1,y=function(r){if(null===r&#124;&#124;"object"!=typeof r&#124;&#124;r.nodeType&#124;&#124;null!==r&#038;&#038;r===r.window)return!1;try{if(r.constructor&#038;&#038;!this.hasOwnProperty.call(r.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0};for("boolean"==typeof e&#038;&#038;(u=e,e=arguments[f]&#124;&#124;{},f++),"object"!=typeof e&#038;&#038;"function"!=typeof e&#038;&#038;(e={}),!1;i>f;f+=1)if(null!==(r=arguments[f]))for(t in r)e!==r[t]&#038;&#038;"undefined"==typeof e[t]&#038;&#038;(u&#038;&#038;r[t]&#038;&#038;(y(r[t])&#124;&#124;(n=Array.isArray(r[t])))?(n?(n=!1,o=e[t]&#038;&#038;Array.isArray(e[t])?e[t]:[]):o=e[t]&#038;&#038;y(e[t])?e[t]:{},e[t]=extend(u,o,r[t])):void 0!==r[t]&#038;&#038;(e[t]=r[t]));return e} And here an example: var object_a = { value_1: 'a', [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>We can find many discussions and solutions about this issue.</p>
<p>In my case the one that worked is <a href="http://stackoverflow.com/a/24248152/1134119">this code</a>.</p>
<p>Below you&#8217;ll find a compressed version of the <code>extend()</code> function (<a href="https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript/24248152#comment75410509_24248152">with a fix</a>):</p>
<pre class="brush:javascript">
function extend(){var r,t,n,o,e=arguments[0]||{},f=1,i=arguments.length,u=!1,y=function(r){if(null===r||"object"!=typeof r||r.nodeType||null!==r&#038;&r===r.window)return!1;try{if(r.constructor&#038;&!this.hasOwnProperty.call(r.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0};for("boolean"==typeof e&#038;&(u=e,e=arguments[f]||{},f++),"object"!=typeof e&#038;&"function"!=typeof e&#038;&(e={}),!1;i>f;f+=1)if(null!==(r=arguments[f]))for(t in r)e!==r[t]&#038;&"undefined"==typeof e[t]&#038;&(u&#038;&r[t]&#038;&(y(r[t])||(n=Array.isArray(r[t])))?(n?(n=!1,o=e[t]&#038;&Array.isArray(e[t])?e[t]:[]):o=e[t]&#038;&y(e[t])?e[t]:{},e[t]=extend(u,o,r[t])):void 0!==r[t]&#038;&(e[t]=r[t]));return e}
</pre>
<p>And here an example:</p>
<pre class="brush:javascript">
var object_a = {
    value_1: 'a',
    value_2: true,
    value_3: 354,
    value_4: [
      'x',
      'y',
      'z'
    ],
    value_5: {
      I: 'I',
      II: 'II',
      III: 'III',
      IV: {
        a: 'A',
        b: 'B'
      },
      V: [
        'elm', {
          5: 'five'
        },
        ['my_array']
      ]
    },
    value_6: function() {
      return "pouet"
    },
    value_7: new Date(2017, 0, 1)
  };
var object_b = {};
// clone object_a into object_b
extend(true, object_b, object_a);
object_a.value_2 = false;
object_a.value_1 = "b";
console.log("A => ", object_a);
console.log("B => ", object_b);
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/04/12/deep-clone-an-object-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Check permissions in Sharepoint based on a PermMask</title>
		<link>https://blog.kodono.info/wordpress/2017/04/06/check-permissions-in-sharepoint-based-on-a-permmask/</link>
					<comments>https://blog.kodono.info/wordpress/2017/04/06/check-permissions-in-sharepoint-based-on-a-permmask/#comments</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 06 Apr 2017 12:41:34 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1773</guid>

					<description><![CDATA[In some cases you could get this kind of hexadecimal numbers from Sharepoint for the PermMask: 0xb008431061, or 0x1b03c4313ff, and so on. To verify the PermMask against the different level of permissions you can proceed with the below method (using functions from core.js): var permMask = '0x1b03c4313ff'; var permissions = new SP.BasePermissions(); permissions.initPropertiesFromJson({High:GetPermMaskH(permMask), Low:GetPermMaskL(permMask)}); // [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In some cases you could get this kind of hexadecimal numbers from Sharepoint for the PermMask: <code>0xb008431061</code>, or <code>0x1b03c4313ff</code>, and so on.</p>
<p>To verify the PermMask against the different level of permissions you can proceed with the below method (using functions from <code>core.js</code>):</p>
<pre class="brush:javascript">
var permMask = '0x1b03c4313ff';
var permissions = new SP.BasePermissions();
permissions.initPropertiesFromJson({High:GetPermMaskH(permMask), Low:GetPermMaskL(permMask)});
// we can now check permissions using SP.BasePermissions.has()
// and we can compare with SP.PermissionKind — see https://msdn.microsoft.com/en-us/library/office/ee556747(v=office.14).aspx
var canEdit = permissions.has(SP.PermissionKind.editListItems);
</pre>
<p>On Sharepoint 2010 <code>GetPermMaskH</code> and <code>GetPermMaskL</code> are not defined, so here is their code:</p>
<pre class="brush:javascript">
function GetPermMaskH(b) {
    var a = b.length;
    return a &lt;= 10 ? 0 : parseInt(b.substring(2, a - 8), 16)
}

function GetPermMaskL(b) {
    var a = b.length;
    return a &lt;= 10 ? parseInt(b) : parseInt(b.substring(a - 8, a), 16)
}
</pre>
<p>It took me many hours to find how to proceed, so I hope it will help some others.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/04/06/check-permissions-in-sharepoint-based-on-a-permmask/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Decode Sharepoint unicode URL</title>
		<link>https://blog.kodono.info/wordpress/2017/02/17/decode-sharepoint-unicode-url/</link>
					<comments>https://blog.kodono.info/wordpress/2017/02/17/decode-sharepoint-unicode-url/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Fri, 17 Feb 2017 10:32:31 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1770</guid>

					<description><![CDATA[Sharepoint encodes the URLs with unicode, so we&#8217;ll see many \u002f to represent /. If you want to decode those unicode strings, you can use this short code: unescape(JSON.parse('"' + s.replace('"', '\\"') + '"'))]]></description>
										<content:encoded><![CDATA[<p>Sharepoint encodes the URLs with unicode, so we&#8217;ll see many <code>\u002f</code> to represent <code>/</code>.</p>
<p>If you want to decode those unicode strings, you can use <a href="http://stackoverflow.com/a/12869914/1134119">this short code</a>:<br />
<code>unescape(JSON.parse('"' + s.replace('"', '\\"') + '"'))</code></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/02/17/decode-sharepoint-unicode-url/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Redirect after Deleting [Sharepoint]</title>
		<link>https://blog.kodono.info/wordpress/2017/02/15/redirect-after-deleting-sharepoint/</link>
					<comments>https://blog.kodono.info/wordpress/2017/02/15/redirect-after-deleting-sharepoint/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 15 Feb 2017 15:42:15 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1768</guid>

					<description><![CDATA[When I open a dialog for an EditFrom and use the &#8220;Delete Item&#8221; button from the ribbon, then the main page is redirected to the related Sharepoint list. This behavior is very bad for the user experience. To change it I used the below Javascript code: // replace the Delete Item default action when into [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>When I open a dialog for an EditFrom and use the &#8220;Delete Item&#8221; button from the ribbon, then the main page is redirected to the related Sharepoint list. This behavior is very bad for the user experience.</p>
<p>To change it I used the below Javascript code:</p>
<pre class="brush:javascript">
// replace the Delete Item default action when into a popup
$(document).ready(function() {
  // if it's in a popup
  if (window !== window.top) {
    $('a[id$="_toolBarTbl_RptControls_diidIODeleteItem"]').attr("href","javascript:commonDeleteItem(); return false")
  }
})
// now when clicking on the Delete item it will call my own function
// here I use http://aymkdn.github.io/SharepointPlus/ to show a waiting message and to delete the current item, and then close the modal
function commonDeleteItem() {
  $SP().waitModalDialog("Deleting...");
  $SP().list("{"+WPQ2FormCtx.ListAttributes.Id+"}").remove({ID:GetUrlKeyValue("ID")}, {
    after:function() {
      $SP().closeModalDialog();
      $SP().closeModalDialog(2);
    }
  })
}
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/02/15/redirect-after-deleting-sharepoint/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to open an Excel document from SharePoint into Chrome/Firefox in readonly/edit mode</title>
		<link>https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/</link>
					<comments>https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 09 Feb 2017 18:07:22 +0000</pubDate>
				<category><![CDATA[Debug]]></category>
		<category><![CDATA[Navigateur]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1760</guid>

					<description><![CDATA[With Sharepoint 2010, when you use Internet Explorer you can open an Office document in readonly or in edit mode. Also, when trying to open an Excel file in Firefox/Chrome it will probably open the ugly xslviewer and won&#8217;t let you deal with your file. After searching a bit about it, I found a clue [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>With Sharepoint 2010, when you use Internet Explorer you can open an Office document in readonly or in edit mode. Also, when trying to open an Excel file in Firefox/Chrome it will probably open the ugly <code>xslviewer</code> and won&#8217;t let you deal with your file.</p>
<p>After searching a bit about it, I found <a href="http://stackoverflow.com/a/30929451/1134119">a clue</a> that helped me to find a good solution: on Firefox/Chrome when you click on an Excel file, you&#8217;ll now have a modal asking if you want to open it in edit or readonly mode!<br />
<img fetchpriority="high" decoding="async" src="https://blog.kodono.info/wordpress/wp-content/uploads/2017/02/opendocuments1.png" alt="" width="310" height="298" class="aligncenter size-full wp-image-1761" srcset="https://blog.kodono.info/wordpress/wp-content/uploads/2017/02/opendocuments1.png 310w, https://blog.kodono.info/wordpress/wp-content/uploads/2017/02/opendocuments1-300x288.png 300w" sizes="(max-width: 310px) 100vw, 310px" /></p>
<p>To achieve this result you have to insert the below Javascript code somewhere into your masterpage:</p>
<pre class="brush:javascript">
/**
 * fix problem with Excel documents on Firefox/Chrome
 * @param  {HTMLElement} p the &lt;A> element
 * @param  {HTMLEvent} a the click event
 * @param  {Boolean} h TRUE
 * @param  {Boolean} e FALSE
 * @param  {Boolean} g FALSE
 * @param  {Strin} k the ActiveX command (e.g. "SharePoint.OpenDocuments.3")
 * @param  {Number} c 0
 * @param  {String} o the activeX command, here we look at "SharePoint.OpenDocuments"
 * @param  {String} m
 * @param  {String} b the replacement URL to the xslviewer
 */
var bak_DispEx;
var modalOpenDocument; // it will be use with the modal
SP.SOD.executeOrDelayUntilEventNotified(function() {
  bak_DispEx = _DispEx;
  _DispEx=function(p, a, h, e, g, k, c, o, m, b, j, l, i, f, d) {
    // if o==="SharePoint.OpenDocuments" &#038;& !IsClientAppInstalled(o)
    // in that case we want to open ask the user if he/she wants to readonly or edit the file
    var fileURL = b.replace(/.*_layouts\/xlviewer\.aspx\?id=(.*)/, "$1");
    if (o === "SharePoint.OpenDocuments" &#038;& !IsClientAppInstalled(o) &#038;& /\.xlsx?$/.test(fileURL)) {
      // if the URL doesn't start with http
      if (!/^http/.test(fileURL)) {
        fileURL = window.location.protocol + "//" + window.location.host + fileURL;
      }
      var ohtml = document.createElement('div');
      ohtml.style.padding = "10px";
      ohtml.style.display = "inline-block";
      ohtml.style.width = "200px";
      ohtml.style.width = "200px";
      ohtml.innerHTML = '&lt;style>'
                      + '.opendocument_button { background-color:#fdfdfd; border:1px solid #ababab; color:#444; display:inline-block; padding: 7px 10px; }'
                      + '.opendocument_button:hover { box-shadow: none }'
                      + '#opendocument_readonly,#opendocument_edit { float:none; font-size: 100%; line-height: 1.15; margin: 0; overflow: visible; box-sizing: border-box; padding: 0; height:auto }'
                      + '.opendocument_ul { list-style-type:none;margin-top:10px;margin-bottom:10px;padding-top:0;padding-bottom:0 }'
                      + '&lt;/style>'
                      + 'You are about to open:'
                      + '&lt;ul class="opendocument_ul">'
                      + '  &lt;li>Name: &lt;b>'+fileURL.split("/").slice(-1)+'&lt;/b>&lt;/li>'
                      + '  &lt;li>From: &lt;b>'+window.location.hostname+'&lt;/b>&lt;/li>'
                      + '&lt;/ul>'
                      + 'How would like to open this file?'
                      + '&lt;ul class="opendocument_ul">'
                      + '  &lt;li>&lt;label>&lt;input type="radio" name="opendocument_choices" id="opendocument_readonly" checked> Read Only&lt;/label>&lt;/li>'
                      + '  &lt;li>&lt;label>&lt;input type="radio" name="opendocument_choices" id="opendocument_edit"> Edit&lt;/label>&lt;/li>'
                      + '&lt;/ul>'
                      + '&lt;div style="text-align: center;margin-top: 20px;">&lt;button type="button" class="opendocument_button" style="background-color: #2d9f2d;color: #fff;" onclick="modalOpenDocument.close(document.getElementById(\'opendocument_edit\').checked)">Open&lt;/button> &lt;button type="button" class="opendocument_button" style="margin-left:10px" onclick="modalOpenDocument.close(-1)">Cancel&lt;/button>&lt;/div>';
      // show the modal
      modalOpenDocument=SP.UI.ModalDialog.showModalDialog({
        html:ohtml,
        dialogReturnValueCallback:function(ret) {
          if (ret!==-1) {
            if (ret === true) { // edit
              // reformat the fileURL
              var ext;
              if (/\.xlsx?$/.test(b)) ext = "ms-excel";
              if (/\.docx?$/.test(b)) ext = "ms-word"; // not currently supported
              fileURL = ext + ":ofe|u|" + fileURL;
            }
            window.location.href = fileURL; // open the file
          }
        }
      });
      a.preventDefault();
      a.stopImmediatePropagation()
      a.cancelBubble = true;
      a.returnValue = false;
      return false;
    }
    return bak_DispEx.apply(this, arguments);
  }
}, "sp.scriptloaded-core.js")
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2017/02/09/how-to-open-an-excel-document-from-sharepoint-files-into-chromefirefox-in-readonlyedit-mode/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Yes, you can be lazy and get more than 5000 SharePoint Items</title>
		<link>https://blog.kodono.info/wordpress/2016/12/06/yes-you-can-be-lazy-and-get-more-than-5000-sharepoint-items/</link>
					<comments>https://blog.kodono.info/wordpress/2016/12/06/yes-you-can-be-lazy-and-get-more-than-5000-sharepoint-items/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Tue, 06 Dec 2016 08:32:04 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1733</guid>

					<description><![CDATA[To reply to this blog post I wanted to share the same thing but with SharepointPlus. To use the paging option and get all the content from a large Sharepoint list you can simply do the below code: $SP().list("My List").get({ fields:"ID,Title", rowlimit:5000, paging:true, progress:function progress(nbItemsLoaded) { // for each new page this function will be [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>To reply to <a href="http://sympmarc.com/2016/11/30/25696/">this blog post</a> I wanted to share the same thing but with <a href="http://aymkdn.github.io/SharepointPlus/">SharepointPlus</a>.</p>
<p>To use the paging option and get all the content from a large Sharepoint list you can simply do the below code:</p>
<pre class="brush:javascript">
$SP().list("My List").get({
  fields:"ID,Title",
  rowlimit:5000,
  paging:true,
  progress:function progress(nbItemsLoaded) {
    // for each new page this function will be called
    console.log("It's still loading... already "+nbItemsLoaded+" items have been loaded!");
  }
}, function(data) {
  console.log(data.length); // -> 23587
  for (var i=0, len=data.length; i&lt;len; i++) {
    console.log(data[i].getAttribute("ID"))
  }
})
</pre>
<p>If you only want to get the first 15,000 items, you can use the option <code>page:3</code>. See <a href="http://aymkdn.github.io/SharepointPlus/symbols/%24SP%28%29.list.html#.get">the documentation</a> to know more.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2016/12/06/yes-you-can-be-lazy-and-get-more-than-5000-sharepoint-items/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Execute an action before saving a form but after the form validation [Sharepoint]</title>
		<link>https://blog.kodono.info/wordpress/2016/11/18/execute-action-before-saving-a-form-and-after-form-validation-sharepoint/</link>
					<comments>https://blog.kodono.info/wordpress/2016/11/18/execute-action-before-saving-a-form-and-after-form-validation-sharepoint/#comments</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Fri, 18 Nov 2016 14:44:22 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1721</guid>

					<description><![CDATA[Let&#8217;s say you want to do an asynchronous request just before saving a Sharepoint form, but after Sharepoint verified all the fields in your form (for mandatory ones, or for format, &#8230;). Here is my solution to do it (using jQuery.Deferred): // this function will do our asynchronous check function beforeSaving() { var deferred=jQuery.Deferred(); setTimeout(function() [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Let&#8217;s say you want to do an asynchronous request just before saving a Sharepoint form, but after Sharepoint verified all the fields in your form (for mandatory ones, or for format, &#8230;). Here is my solution to do it (using jQuery.Deferred):</p>
<pre class="brush:javascript">
// this function will do our asynchronous check
function beforeSaving() {
  var deferred=jQuery.Deferred();
  setTimeout(function() {
    alert("Test Complete!")
    deferred.reject(); // if the test failed
    // or deferred.resolve() to valid the test
  }, 2000)
  return deferred;
}
// force PostBackRequired to true in the context, otherwise it won't work if you open it into a modal
WPQ2FormCtx.PostBackRequired=true;
// we override SPClientForms.ClientFormManager.SubmitClientForm
SPClientForms.ClientFormManager.SubmitClientForm=function(b){
  var a=SPClientForms.ClientFormManager.GetClientForm(b);
  var res = (a!=null&#038;&a.SubmitClientForm());
  // if the form is not valid, then res===true
  if (res === true) return true;
  else {
    // at this stage, all fields' value have been saved into a hidden input
    // e.g. document.querySelector('input[type="hidden"][id$="Field_x0020_Name"]')
    // all these saved values will be sent back to the server when "WebForm_DoPostBackWithOptions" is executed

    // if the form is valid we now want to do our asynchronous check
    beforeSaving().done(function() {
      // our test is valid too so we can send the form to the server
      WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions($get(WPQ2FormCtx.SubmitButtonID).name, "", true, "", "", false, true))
    }).fail(function() {
      // if it fails we just unblock the save button
      $get(WPQ2FormCtx.SubmitButtonID).disabled=false;
    })
  }
  // to make sure the form won't be submitted yet
  return true;
};
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2016/11/18/execute-action-before-saving-a-form-and-after-form-validation-sharepoint/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Hide a field into a form with JSLink based on field&#8217;s description [Sharepoint]</title>
		<link>https://blog.kodono.info/wordpress/2016/11/03/hide-a-field-into-a-form-with-jslink-based-on-fields-description-sharepoint/</link>
					<comments>https://blog.kodono.info/wordpress/2016/11/03/hide-a-field-into-a-form-with-jslink-based-on-fields-description-sharepoint/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 03 Nov 2016 15:02:07 +0000</pubDate>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1698</guid>

					<description><![CDATA[On Sharepoint 2013 I was trying to hide a field (the complete row) based on some elements into its description. To do so we will call our file using the JSLink (see my previous post about it). The JS file looks like that: (function() { // do some actions as soon as the fields are [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>On Sharepoint 2013 I was trying to hide a field (the complete row) based on some elements into its description.</p>
<p>To do so we will call our file using the JSLink (see <a href="https://blog.kodono.info/wordpress/2016/08/25/bypass-a-lookup-field-not-displayed-because-of-threshold-on-newform-and-editform-sharepoint-2013/">my previous post</a> about it).<br />
The JS file looks like that:</p>
<pre class="brush:javascript">
(function() {
  // do some actions as soon as the fields are shown
  var loadAfterForm = {
    Templates: {
      OnPostRender:function(ctx) {
        // hide the field/row when "[INTERNAL USE - DO NOT CHANGE]" is detected in the field's description
        if (ctx.ListSchema.Field[0].Description.indexOf('[INTERNAL USE - DO NOT CHANGE]') > -1) {
          // get the element that represents the field
          var elem = document.querySelector('[id^="'+ctx.ListSchema.Field[0].Name +'_'+ ctx.ListSchema.Field[0].Id+'"]');
          while (elem) {
            elem = elem.parentNode;
            if (elem) {
              if (elem.tagName==="BODY") break;
              if (elem.tagName === "TD" &#038;& elem.className.indexOf("ms-formbody") > -1) {
                // hide the whole row
                elem.parentNode.style.display="none";
                break;
              }
            }
          }
        }
      }
    }
  }
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(loadAfterForm);
})();
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2016/11/03/hide-a-field-into-a-form-with-jslink-based-on-fields-description-sharepoint/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Load a script once a DispForm is fully shown in Sharepoint 2013</title>
		<link>https://blog.kodono.info/wordpress/2016/05/30/load-a-script-once-a-dispform-is-fully-shown-in-sharepoint-2013/</link>
					<comments>https://blog.kodono.info/wordpress/2016/05/30/load-a-script-once-a-dispform-is-fully-shown-in-sharepoint-2013/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 30 May 2016 10:48:54 +0000</pubDate>
				<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<category><![CDATA[Sharepoint 2013]]></category>
		<guid isPermaLink="false">https://blog.kodono.info/wordpress/?p=1654</guid>

					<description><![CDATA[Sharepoint 2013 introduced the JSLink. This is very useful to play with forms and views. My attempt here is to remove some rows from the DispForm. To do so I needed to trigger an action as soon as the fields rendering has been done. After different tries, I finally came up with the PostRender option. [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Sharepoint 2013 introduced the <a href="http://jsuhail.blogspot.fr/2014/09/client-side-rendering-using-jslink-post_30.html">JSLink</a>. This is very useful to play with forms and views.</p>
<p>My attempt here is to remove some rows from the DispForm. To do so I needed to trigger an action as soon as the fields rendering has been done. After different tries, I finally came up with the <code>PostRender</code> option.</p>
<pre class="brush:javascript">
// https://gist.github.com/Aymkdn/98acfbb46fbe7c1f00cdd3c753520ea8
function loadExt(e,t){var s=this;s.files=e,s.js=[],s.head=document.getElementsByTagName("head")[0],s.after=t||function(){},s.loadStyle=function(e){var t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e,s.head.appendChild(t)},s.loadScript=function(e){var t=document.createElement("script");t.type="text/javascript",t.src=s.js[e];var a=function(){++e&lt;s.js.length?s.loadScript(e):s.after()};t.onload=function(){a()},s.head.appendChild(t)};for(var a=0;a&lt;s.files.length;a++)/\.js$|\.js\?/.test(s.files[a])&#038;&s.js.push(s.files[a]),/\.css$|\.css\?/.test(s.files[a])&#038;&s.loadStyle(s.files[a]);s.js.length>0?s.loadScript(0):s.after()}

// verify when all scripts have been loaded
var loadExtLoaded = false;
function checkExt(ctx) {
  if (loadExtLoaded) {
    // here you can call a function that is in one of the called script
  } else {
    setTimeout(function() { checkExt(ctx) }, 50);
  }
}
loadExt([
  'file_you_want_to_load.js',
  'style_you_want_to_load.css',
  'no_cache_file.js?timestamp='+(Date.now())
], function() {
  loadExtLoaded=true;
});

(function() {
  function onLoad(ctx) {
    checkExt(ctx);
  }

  // do some actions as soon as the fields are shown
  var loadAfterForm = {
    Templates: {
      OnPostRender:function(ctx) {
         // only trigger when everything is loaded
        // --> ctx.ListData.Items[0] all the fields
        if (ctx.ListSchema.Field[0].Name === "Attachments") {
          onLoad(ctx)
        }
      }
    }
  }
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(loadAfterForm);
})();
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2016/05/30/load-a-script-once-a-dispform-is-fully-shown-in-sharepoint-2013/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Play with ribbon on Sharepoint</title>
		<link>https://blog.kodono.info/wordpress/2016/03/17/play-with-ribbon-on-sharepoint/</link>
					<comments>https://blog.kodono.info/wordpress/2016/03/17/play-with-ribbon-on-sharepoint/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 17 Mar 2016 15:49:50 +0000</pubDate>
				<category><![CDATA[Astuce]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1604</guid>

					<description><![CDATA[In Sharepoint 2010 and 2013, there are some existing functions to deal with the ribbon. Below an example of what we can do: // we need the file "sp.ribbon.js" SP.SOD.executeOrDelayUntilScriptLoaded(function () { // use PageManager var pm = SP.Ribbon.PageManager.get_instance(); // define a function to call when the ribbon is loaded var DoSomethingWithRibbon=function(ribbon) { // For [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In Sharepoint 2010 and 2013, there are some existing functions to deal with the ribbon.</p>
<p>Below an example of what we can do:</p>
<pre class="brush:javascript">
// we need the file "sp.ribbon.js"
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
  // use PageManager
  var pm = SP.Ribbon.PageManager.get_instance();

  // define a function to call when the ribbon is loaded
  var DoSomethingWithRibbon=function(ribbon) {
    // For example, we can select the "Browse" tab
    ribbon.selectTabById("Ribbon.ListForm.Display", true);
    // Note: You can explore the DOM to find the related IDs
    // other example "Edit" tab is "Ribbon.ListForm.Edit"
  
    // We can now remove the "Edit" tab
    ribbon.removeChild("Ribbon.ListForm.Edit");
  }

  // perform an action when the ribbon has been inited
  pm.add_ribbonInited(function () {
    DoSomethingWithRibbon(pm.get_ribbon())
  });

  // if the ribbon is already loaded
  var ribbon = null;
  try {
    // get an instance of the ribbon
    ribbon = pm.get_ribbon();
  } catch (e) {}
  if (!ribbon) {
    if (typeof(_ribbonStartInit) == "function")
      _ribbonStartInit(_ribbon.initialTabId, false, null);
  } else {
    DoSomethingWithRibbon(ribbon);
  }

}, "sp.ribbon.js");
</pre>
<p>And there are also solutions to add stuff to the ribbon. I have to dig into these solutions&#8230; In the meantime you can try <a href="https://dbremes.wordpress.com/2011/01/16/theres-a-javascript-api-for-creating-ribbons/">this blog post</a>, or <a href="http://www.umtsoftware.com/blog/creating-sharepoint-ribbon-elements-in-javascript/">this one</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2016/03/17/play-with-ribbon-on-sharepoint/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Quickly find if an object is an array [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2015/12/15/quickly-find-if-an-object-is-an-array-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/12/15/quickly-find-if-an-object-is-an-array-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Tue, 15 Dec 2015 10:21:56 +0000</pubDate>
				<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1580</guid>

					<description><![CDATA[You could use Array.isArray(obj) but it&#8217;s not available for IE8 and it doesn&#8217;t seem very good on the performance side. The best one on the different browsers is to test: obj instanceof Array]]></description>
										<content:encoded><![CDATA[<p>You could use <code>Array.isArray(obj)</code> but it&#8217;s not available for IE8 and it doesn&#8217;t seem very good on the performance side. The <a href="http://jsperf.com/js-isarray-comparison">best one on the different browsers</a> is to test: <code>obj instanceof Array</code></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/12/15/quickly-find-if-an-object-is-an-array-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Pure Javascript Drag and Drop cross browser from IE8</title>
		<link>https://blog.kodono.info/wordpress/2015/11/10/pure-javascript-drag-and-drop-cross-browser-from-ie8/</link>
					<comments>https://blog.kodono.info/wordpress/2015/11/10/pure-javascript-drag-and-drop-cross-browser-from-ie8/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Tue, 10 Nov 2015 12:13:12 +0000</pubDate>
				<category><![CDATA[Navigateur]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1568</guid>

					<description><![CDATA[I was looking for a simple JavaScript to drag a div element around, and that would work with IE8 and without any third party libraries (like jQuery). It&#8217;s been very difficult to find a simple code ! Finally http://news.qooxdoo.org/mouse-capturing saved me with some code&#8230; but there was still a problem with IE8 due to the [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I was looking for a simple JavaScript to drag a div element around, and that would work with IE8 and without any third party libraries (like jQuery). It&#8217;s been very difficult to find a simple code !</p>
<p>Finally <a href="http://news.qooxdoo.org/mouse-capturing">http://news.qooxdoo.org/mouse-capturing</a> saved me with some code&#8230; but there was still a problem with IE8 due to the mouse that wasn&#8217;t losing capture. So after some research, I&#8217;ve been able to create a code that works for IE8 and modern browsers:</p>
<pre class="brush:html">
&lt;!DOCTYPE html>
&lt;html>
  &lt;head>
  &lt;/head>
  &lt;body>
    &lt;!-- `top` and `left` must be defined into the `style` -->
    &lt;div id="popup" style="background-color:green;position:absolute;top:0px;left:0px;width:250px;height:250px;z-index:9999;box-shadow: 6px 6px 5px #888888;border-radius:6px;border:1px solid #4f4f4f;">
      &lt;div id="popup_bar" style="width:100%;background-color:#aaff66;position:relative;top:0;border-radius:6px 6px 0 0; text-align:center;height:24px;cursor:move">Title&lt;/div>
      &lt;p>Content of the popup&lt;/p>
    &lt;/div>
  &lt;/body>
&lt;script>/* see below for the javascript */&lt;/script>
&lt;/html>
</pre>
<pre class="brush:javascript">
!function() {
  function addListener(element, type, callback, capture) {
    if (element.addEventListener) {
      element.addEventListener(type, callback, capture);
    } else {
      element.attachEvent("on" + type, callback);
    }
  }
  
  function draggable(element) {
    var dragging = null;
  
    addListener(element, "mousedown", function(e) {
      var e = window.event || e;
      dragging = {
        mouseX: e.clientX,
        mouseY: e.clientY,
        startX: parseInt(element.style.left),
        startY: parseInt(element.style.top)
      };
      if (element.setCapture) element.setCapture();
    });
  
    addListener(element, "losecapture", function() {
      dragging = null;
    });
  
    addListener(document, "mouseup", function() {
      dragging = null;
      if (document.releaseCapture) document.releaseCapture();
    }, true);
  
    var dragTarget = element.setCapture ? element : document;
  
    addListener(dragTarget, "mousemove", function(e) {
      if (!dragging) return;
  
      var e = window.event || e;
      var top = dragging.startY + (e.clientY - dragging.mouseY);
      var left = dragging.startX + (e.clientX - dragging.mouseX);
  
      element.style.top = (Math.max(0, top)) + "px";
      element.style.left = (Math.max(0, left)) + "px";
    }, true);
  };    
  
  // here you must define the element to be draggable
  draggable(document.getElementById("popup"));
}();
</pre>
<p>You can test this code with <a href="http://github-proxy.kodono.info/?q=https://gist.githubusercontent.com/Aymkdn/35a7504031642211101e/raw/2b0d174d68cf38d6a4affb8d551d919c16cb32e0/popup_draggable.html">the demo</a> or <a href="https://gist.github.com/Aymkdn/35a7504031642211101e">see it on Gist</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/11/10/pure-javascript-drag-and-drop-cross-browser-from-ie8/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to expand Sharepoint 2013 calendar by default [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2015/11/02/how-to-expand-sharepoint-2013-calendar-by-default-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/11/02/how-to-expand-sharepoint-2013-calendar-by-default-javascript/#comments</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 02 Nov 2015 15:16:32 +0000</pubDate>
				<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharepoint]]></category>
		<category><![CDATA[Sharepoint 2013]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1562</guid>

					<description><![CDATA[This code has been tested for Sharepoint 2013 only. It permits to expand by default (so as soon as the page is loaded) the events in the Month calendar view. See here a solution for Sharepoint 2010. Tested with IE8 and Firefox 41. You&#8217;ll have to add the below JavaScript code into your calendar page: [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>This code has been tested for Sharepoint 2013 only. It permits to expand by default (so as soon as the page is loaded) the events in the Month calendar view.</p>
<p><a href="http://blog.kodono.info/wordpress/2014/12/18/how-to-expand-sharepoint-2010-calendar-by-default-javascript/">See here a solution for Sharepoint 2010</a>.</p>
<p>Tested with IE8 and Firefox 41. You&#8217;ll have to add the below JavaScript code into your calendar page:</p>
<pre class="brush:javascript">
// the below function simulate a click on a link
function fireEventClick(elem){
    if(document.createEvent){                                                 
      var e = document.createEvent('MouseEvents');
      e.initMouseEvent('click', /* Event type */
      true, /* Can bubble */
      true, /* Cancelable */
      document.defaultView, /* View */
      1, /* Mouse clicks */
      0, /* Screen x */
      0, /* Screen y */
      0, /* Client x */
      0, /* Client y */
      false, /* Ctrl */
      false, /* Alt */
      false, /* Shift */
      false, /* Meta */
      0, /* Button */
      null); /* Related target */
      elem.dispatchEvent(e);                     
    } else { // pour IE
      elem.click();
    }
}

// Expand the events
// because Sharepoint redraw ALL the events when we click on Expand, then we need a special recurrent function
function ExpandEvents(idx) {
  var a = document.querySelectorAll('a[evtid="expand_collapse"]');
  if (idx &lt; a.length) {
    if (a[idx].parentNode.getAttribute("_expand") !== "collapse") fireEventClick(a[idx]);
    ExpandEvents(++idx);
  }
}

function onCalendarGridsRendered(){
  setTimeout(function() {
    ExpandEvents(0)
  }, 250)
}

// some code reused from http://www.codeproject.com/Tips/759006/Enhancing-SharePoint-Calendar-sp-ui-applicationpag
SP.SOD.executeOrDelayUntilScriptLoaded(function () {
    //Week or Day Calendar View
    SP.UI.ApplicationPages.DetailCalendarView.prototype.renderGrids_Old = SP.UI.ApplicationPages.DetailCalendarView.prototype.renderGrids;
    SP.UI.ApplicationPages.DetailCalendarView.prototype.renderGrids = function SP_UI_ApplicationPages_DetailCalendarView$renderGrids($p0) {
      this.renderGrids_Old($p0);
      onCalendarGridsRendered();
    };
    
    //Month Calendar View
    SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids_Old = SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids;
    SP.UI.ApplicationPages.SummaryCalendarView.prototype.renderGrids = function SP_UI_ApplicationPages_SummaryCalendarView$renderGrids($p0) {
      this.renderGrids_Old($p0);
      onCalendarGridsRendered();
    };
    
    ExpandEvents(0)
}, "SP.UI.ApplicationPages.Calendar.js");
</pre>
<p>And we can hide the &#8220;Collapse&#8221; links with one line of CSS:</p>
<pre class="brush:css">
.ms-cal-nav[evtid="expand_collapse"] { display: none !important }
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/11/02/how-to-expand-sharepoint-2013-calendar-by-default-javascript/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>Transform pseudo currency to number in JavaScript</title>
		<link>https://blog.kodono.info/wordpress/2015/10/28/transform-pseudo-currency-to-number-in-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/10/28/transform-pseudo-currency-to-number-in-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Wed, 28 Oct 2015 11:39:41 +0000</pubDate>
				<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1559</guid>

					<description><![CDATA[In JavaScript I want to change some formatted numbers to a regular number. The code might be look like that: var aNb=[ 1500, "1,500", "15,00", "1,500,000", "1,500,000.25", "1000.25", "1 000 000"]; for (var i=0; i &#60; aNb.length; i++) { var nb = aNb[i] + ""; if (nb.split(",").length &#60;= 2) nb = nb.replace(/,(\d{2})$/,".$1"); nb = nb.replace(/[^\d\.\-]/g, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>In JavaScript I want to change some formatted numbers to a regular number.</p>
<p>The code might be look like that:</p>
<pre class="brush:javascript">
var aNb=[ 1500, "1,500", "15,00", "1,500,000", "1,500,000.25", "1000.25", "1 000 000"];
for (var i=0; i &lt; aNb.length; i++) {
  var nb = aNb[i] + "";
  if (nb.split(",").length &lt;= 2)
    nb = nb.replace(/,(\d{2})$/,".$1");
  nb = nb.replace(/[^\d\.\-]/g, '').replace(/\s/g,"")
  
  console.log(aNb[i], "=>", nb);
}

/* result:
1500 => 1500
1,500 => 1500
15,00 => 15.00
1,500,000 => 1500000
1,500,000.25 => 1500000.25
1000.25 => 1000.25
1 000 000 => 1000000
*/
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/10/28/transform-pseudo-currency-to-number-in-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Détecter la version d&#8217;IE [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2015/03/23/detecter-la-version-die-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/03/23/detecter-la-version-die-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 23 Mar 2015 11:53:52 +0000</pubDate>
				<category><![CDATA[Astuce]]></category>
		<category><![CDATA[Navigateur]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1481</guid>

					<description><![CDATA[Via http://tanalin.com/en/articles/ie-version-js/ on trouve un moyen simple de détecter la version d&#8217;IE : var IE8 = !!(document.all &#038;&#038; document.querySelector &#038;&#038; !document.addEventListener); // -> true/false var IE9 = !!(document.all &#038;&#038; document.addEventListener &#038;&#038; !window.atob); // -> true/false var IE10 = !!(document.all &#038;&#038; window.atob); // -> true/false On peut aussi utiliser les conditionals compilation: var ieVersion = /*@cc_on [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Via <a href="http://tanalin.com/en/articles/ie-version-js/">http://tanalin.com/en/articles/ie-version-js/</a> on trouve un moyen simple de détecter la version d&#8217;IE :</p>
<pre class="brush:javascript">
var IE8 = !!(document.all &#038;& document.querySelector &#038;& !document.addEventListener); // -> true/false
var IE9 = !!(document.all &#038;& document.addEventListener &#038;& !window.atob); // -> true/false
var IE10 = !!(document.all &#038;& window.atob); // -> true/false
</pre>
<p>On peut aussi utiliser les <em>conditionals compilation</em>:</p>
<pre class="brush:javascript">
var ieVersion = /*@cc_on (function() {switch(@_jscript_version) { case 5.8: return 8; case 9: return 9; case 10: return 10;}})() || @*/ 0; // -> 8, 9 ou 10
</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/03/23/detecter-la-version-die-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Get window/viewport/document height and width [JavaScript]</title>
		<link>https://blog.kodono.info/wordpress/2015/03/23/get-window-viewport-document-height-and-width-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/03/23/get-window-viewport-document-height-and-width-javascript/#respond</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Mon, 23 Mar 2015 10:19:34 +0000</pubDate>
				<category><![CDATA[Astuce]]></category>
		<category><![CDATA[Navigateur]]></category>
		<category><![CDATA[Niveau débutant]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1477</guid>

					<description><![CDATA[Via andylangton and james.padolsey we can find the viewport and document height/width in JavaScript: function getPageSize() { var vw = {width:0, height:0}; var doc = {width:0, height:0}; var w=window, d=document, dde=d.documentElement, db=d.getElementsByTagName('body')[0]; // viewport size vw.width = w.innerWidth&#124;&#124;dde.clientWidth&#124;&#124;db.clientWidth; vw.height = w.innerHeight&#124;&#124;dde.clientHeight&#124;&#124;db.clientHeight; // document size doc.width = Math.max(db.scrollWidth, dde.scrollWidth, db.offsetWidth, dde.offsetWidth, db.clientWidth, dde.clientWidth); doc.height = Math.max(db.scrollHeight, [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>Via <a href="http://andylangton.co.uk/blog/development/get-viewport-size-width-and-height-javascript">andylangton</a> and <a href="http://james.padolsey.com/snippets/get-document-height-cross-browser/">james.padolsey</a> we can find the viewport and document height/width in JavaScript:</p>
<pre class="brush:javascript">
function getPageSize() {
  var vw = {width:0, height:0};
  var doc = {width:0, height:0};
  var w=window, d=document, dde=d.documentElement, db=d.getElementsByTagName('body')[0];
  
  // viewport size
  vw.width  = w.innerWidth||dde.clientWidth||db.clientWidth;
  vw.height = w.innerHeight||dde.clientHeight||db.clientHeight;

  // document size
  doc.width  = Math.max(db.scrollWidth, dde.scrollWidth, db.offsetWidth, dde.offsetWidth, db.clientWidth, dde.clientWidth);
  doc.height = Math.max(db.scrollHeight, dde.scrollHeight, db.offsetHeight, dde.offsetHeight, db.clientHeight, dde.clientHeight);
  
  // if IE8 there is a bug with 4px
  if (!!(document.all &#038;& document.querySelector &#038;& !document.addEventListener) &#038;& (vw.width+4 == doc.width) &#038;& (vw.height+4 == doc.height)) {
    vw.width=doc.width;
    vw.height=doc.height;
  }
  
   return {vw:vw, doc:doc};
}

getPageSize(); // -> {vw: { width:xxx, height:xxx }, doc: { width:xxx, height:xxx } }
</pre>
<p>It should work for IE8-IE10 and all modern browsers.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/03/23/get-window-viewport-document-height-and-width-javascript/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Autosize a text to fit into a div in pure/native JavaScript</title>
		<link>https://blog.kodono.info/wordpress/2015/03/12/autosize-a-text-to-fit-into-a-div-in-purenative-javascript/</link>
					<comments>https://blog.kodono.info/wordpress/2015/03/12/autosize-a-text-to-fit-into-a-div-in-purenative-javascript/#comments</comments>
		
		<dc:creator><![CDATA[Aymeric]]></dc:creator>
		<pubDate>Thu, 12 Mar 2015 08:44:38 +0000</pubDate>
				<category><![CDATA[Astuce]]></category>
		<category><![CDATA[Niveau intermédiaire]]></category>
		<category><![CDATA[Programmation]]></category>
		<category><![CDATA[Web Design]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[javascript]]></category>
		<guid isPermaLink="false">http://blog.kodono.info/wordpress/?p=1470</guid>

					<description><![CDATA[I was looking for a very tiny and light solution to fit a text inside a box. The box&#8217; height and width are fixed. I only found some great solutions like BigText but I didn&#8217;t want to have jQuery loaded. Finally I found some code on StackOverflow and also at Coderwall. I created my own [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>I was looking for a very tiny and light solution to fit a text inside a box. The box&#8217; height and width are fixed. I only found some great solutions like <a href="https://github.com/zachleat/BigText">BigText</a> but I didn&#8217;t want to have jQuery loaded.</p>
<p>Finally I found some code on StackOverflow and also at <a href="https://coderwall.com/p/_8jxgw/autoresize-text-to-fit-into-a-div-width-height">Coderwall</a>. I created my own solution that could only work with my own HTML code&#8230; but I share it here, maybe that could help someone else.</p>
<p>The HTML code:</p>
<pre class="brush:html">
  <div class="ribbon-front">
    <span>This is my text !</span>
  </div>
</pre>
<p>The related CSS code:</p>
<pre class="brush:css">
.ribbon-front { overflow:hidden }
</pre>
<p>And the JavaScript code:</p>
<pre class="brush:javascript">
var autoSizeText = function(selector) {
  "use strict";
  var el, elements, i, len, style, fontSize, IEoffsetHeight;
  elements = document.querySelectorAll(selector);
  if (elements.length &lt;= 0) return;
  
  for (i=0, len = elements.length; i &lt; len; i++) {
    el = elements[i];

    // we start from 0px and we grow by 0.5 until the content is too large
    fontSize=0;
    el.style.fontSize = "0px";
    // fix for all IE : I cache the offsetHeight, and if it becomes really bigger than the previous value, then we stop!
    IEoffsetHeight = el.offsetHeight;
    // check if our content is out its box
    while (el.scrollHeight===0 || el.scrollHeight >= el.offsetHeight) {
      fontSize += 0.5;
      el.style.fontSize = fontSize + 'px';

      if (el.offsetHeight - IEoffsetHeight > 10) break;
      IEoffsetHeight = el.offsetHeight;
    }
    el.style.fontSize = (fontSize - 0.5) + 'px';
  }
};
autoSizeText('.ribbon-front > span');
</pre>
<p>It works for IE8-IE10 and with all modern browsers.</p>
<p>You can see a demo at <a href="http://codepen.io/Aymkdn/pen/jEeaPV">codepen</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.kodono.info/wordpress/2015/03/12/autosize-a-text-to-fit-into-a-div-in-purenative-javascript/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
	</channel>
</rss>
