<?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>jQuery Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/jquery/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Mon, 12 Aug 2024 15:11:18 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Create Custom HTML Forms for SharePoint with this jQuery Plugin</title>
		<link>https://michaelsoriano.com/sharepoint-forms-custom-html/</link>
					<comments>https://michaelsoriano.com/sharepoint-forms-custom-html/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 21 Nov 2017 17:32:54 +0000</pubDate>
				<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6024</guid>

					<description><![CDATA[<p>There is a big need to build fully customizable forms in SharePoint. I have tried several form builders, but wasn&#8217;t really happy with the restrictions that it comes with. So I wrote this plugin that will create HTML forms in SharePoint. It requires very little code (it&#8217;s all HTML). But the most important thing is [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/sharepoint-forms-custom-html/">Create Custom HTML Forms for SharePoint with this jQuery Plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is a big need to build fully customizable forms in SharePoint. I have tried several form builders, but wasn&#8217;t really happy with the restrictions that it comes with. So I wrote this plugin that will create HTML forms in SharePoint. It requires very little code (<em>it&#8217;s all</em> HTML). But the most important thing is &#8211; it&#8217;s customizable.</p>



<p>There is basically no limit on what you can do.</p>



<p>The gist of it is, all you have to do is match the column names in SharePoint &#8211; to the field in the List. That also means you can arrange the fields, labels, messaging, colors &#8211; just about anything you want.</p>



<p>Again, it&#8217;s all HTML.</p>



<p class="btn"><a href="https://github.com/michaelsoriano/sp-forms">View in GitHub</a></p>



<p>This is a jQuery plugin, so it needs jQuery. The optional Bootstrap CSS can also be added (not required) &#8211; to get you a jump ahead on responsive and styles. The output will be something like below:</p>



<p><br><img fetchpriority="high" decoding="async" width="725" height="675" class="alignnone size-full wp-image-6234" style="border: 1px solid #ebebeb;" src="https://michaelsoriano.com/wp-content/uploads/2017/11/submit.gif" alt="submit form"></p>



<p>The best way to get up and running is by downloading the files editing the HTML. That&#8217;s all. The types of fields (IN THE HTML) that are supported are:</p>



<ul class="wp-block-list">
<li>text</li>



<li>select (drop down lists)</li>



<li>checkbox &#8211; (multiple values)</li>



<li>radio buttons &#8211; (single value)</li>



<li>textarea (multi line text)</li>



<li>file (upload an attachment)</li>
</ul>



<p>There is built-in input validation, loading image, &#8220;thank you&#8221; and &#8220;error&#8221; messaging. Again, you customize these fields by simply updating HTML.</p>



<h3 class="wp-block-heading">How does the Form link with the SharePoint List?</h3>



<p>The HTML part of the form connects with the list via &#8220;attributes&#8221;. To be exact, &#8220;data-list-name&#8221; refers to the List name, and each field will have a &#8220;name&#8221; attribute which refers to the column in your said SharePoint list.</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;div data-list-name="sp-forms-form2" ... ></code></pre>



<p>The above shows that we&#8217;re connecting to &#8220;<strong>sp-forms-form2</strong>&#8221; list. This DIV is not exactly a &#8220;Form&#8221; &#8211; but a wrapper for all of the fields, messaging and buttons that we need. So this DIV is very important.</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;input name="Title" ... /></code></pre>



<p>The above field shows that we&#8217;re connecting to the column &#8220;<strong>Title</strong>&#8221; in the &#8220;<strong>sp-forms-form2</strong>&#8221; list.<br>Easy enough? Let&#8217;s continue.</p>



<div style="background: #fff6c8; padding: 15px 25px; margin-bottom: 25px; margin-top: 20px; border-top: 1px solid #e2dbb5; border-bottom: 1px solid #e2dbb5;"><strong>Important: </strong>You have to know that all of the fields from this form will be saved your list using the &#8220;text&#8221; datatype, except a &#8220;textarea&#8221; &#8211; which will be a &#8220;Multiple lines of text&#8221;.</div>



<figure class="wp-block-image"><img decoding="async" width="572" height="406" src="https://michaelsoriano.com/wp-content/uploads/2017/11/create-column.png" alt="column create" class="wp-image-6227" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/create-column.png 572w, https://michaelsoriano.com/wp-content/uploads/2017/11/create-column-300x213.png 300w" sizes="(max-width: 572px) 100vw, 572px" /></figure>



<h4 class="wp-block-heading">Do not use any type &#8211; it will not insert.</h4>



<p>Again, use only &#8220;Single line of text&#8221; for all fields except a &#8220;textarea&#8221; &#8211; which is &#8220;Multiple lines of text&#8221;.&nbsp; *All values from the form will be inserted as plain text. Checkbox (multiple values) will be separated by a semicolon, but still as text.</p>



<h3 class="wp-block-heading">How to add validation?</h3>



<p>For each field, you can a set of validation rules. For now, we only have &#8220;required&#8221;, &#8220;date&#8221;, &#8220;email&#8221; and &#8220;phone&#8221;. Simply add the rules to the input/textarea/select as an attribute called &#8220;<strong>data-rules</strong>&#8220;. And if you need to use more than one, simply separate it with a pipe &#8220;|&#8221;.</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;input data-rules="required|email" ...</code></pre>



<p>The output will look behave like below:</p>



<p><img decoding="async" width="725" height="321" class="alignnone size-full wp-image-6235" style="border: 1px solid #ebebeb;" src="https://michaelsoriano.com/wp-content/uploads/2017/11/validation.gif" alt="validation"></p>



<p>Are you still with me? Awesome.</p>



<h3 class="wp-block-heading">How to add a Drop Down List?</h3>



<p>A drop down list is simply a &#8220;<strong>select</strong>&#8221; tag in HTML. It&#8217;s basically a select tag, with &#8220;options&#8221; inside it. The &#8220;options&#8221; are the drop down values. It looks something like below:</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;select name="countries">
   &lt;option value="">--&lt;/option>
   &lt;option value="USA">USA&lt;/option>
   ...
   ...
   ...
&lt;/select></code></pre>



<p>Simply add more options to the &#8220;select&#8221; tag to build your drop down list.</p>



<p><strong>How about a textarea, checkbox and radio buttons?</strong> </p>



<p>Those are all in the <a href="https://github.com/michaelsoriano/sp-forms/blob/master/sp-forms.html">demo HTML</a>: It is fully documented and you should be able to figure it out easily. Note that you will need to open this in an HTML editor such as <a href="https://notepad-plus-plus.org/">Notepad++</a> or <a href="https://code.visualstudio.com/">VSCode</a>. Don&#8217;t do regular notepad. Just don&#8217;t.</p>



<p><strong>How about People pickers? Date Pickers?</strong></p>



<p>The plugin itself doesn&#8217;t have it. But its just HTML + JavaScript. Simply add them on document ready. That&#8217;s the beauty of this plugin. You&#8217;re free to do anything you want because you&#8217;re dealing with the code.</p>



<p><strong>How to get the label &#8220;inside&#8221; the text input?</strong></p>



<p>This one is a little tricky. I find it easier to use the &#8220;placeholder&#8221; attribute, than to use a &#8220;label&#8221;. So do something like below:</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;input placeholder="Label here..." ></code></pre>



<p>Anything else that you want to do with the labels and fields should be doable. For example, making the fonts bigger, making the widths of the fields wider &#8211; adding plugins, it&#8217;s completely up to you.</p>



<h3 class="wp-block-heading">What happens when I click &#8220;Submit&#8221;</h3>



<p>Clicking submit will add the record into the list that you&#8217;ve added inside the list that you&#8217;ve specified in the &#8220;data-list-name&#8221; wrapper that we have.</p>



<p>Let&#8217;s say you have everything in place, a new record will go inside your list once you click &#8220;<strong>Submit</strong>&#8220;:</p>



<p><img decoding="async" width="750" height="421" class="alignnone size-full wp-image-6231" src="https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted.png" alt="item inserted" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted.png 750w, https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted-300x168.png 300w" sizes="(max-width: 750px) 100vw, 750px" /></p>



<p><strong>Can I view the submitted record?</strong></p>



<p>By default, as soon as the form submits &#8211; it goes to the newly added record. This means that the url will change to a:</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">http://yoursite.com/yourpage.aspx?form1=25</code></pre>



<p>This will be the &#8220;permanent&#8221; url for the record. If you want to go back to a black form &#8211; simply remove the &#8220;?form1=xxx&#8221; from the address bar.</p>



<p>In the default &#8220;Thank you&#8221; message there is a link to create another record:</p>



<p><img decoding="async" width="426" height="318" class="alignnone size-full wp-image-6251" src="https://michaelsoriano.com/wp-content/uploads/2017/11/add-another.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/add-another.png 426w, https://michaelsoriano.com/wp-content/uploads/2017/11/add-another-300x224.png 300w" sizes="(max-width: 426px) 100vw, 426px" /></p>



<p>Clicking this link will reload the page &#8211; with the form fields ready to go.</p>



<p><strong>Can I customize the &#8220;Thank You&#8221; message?</strong></p>



<p>Yes definitely. Again, go to the HTML and you will see the thank you messaging wrapped in it&#8217;s own DIV:</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;div class="success-message" style="display:none;">
   Thank you for your submission. Click Here ...
&lt;/div></code></pre>



<p><strong>Where does the attachment go?</strong></p>



<p>The input field of type &#8220;file&#8221; and MUST be named &#8220;<strong>attachment</strong>&#8221; will add the file as an &#8220;attachment&#8221; to the list item:</p>



<p><img decoding="async" width="616" height="421" class="alignnone size-full wp-image-6232" src="https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted-w-attachment.png" alt="item inserted" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted-w-attachment.png 616w, https://michaelsoriano.com/wp-content/uploads/2017/11/item-inserted-w-attachment-300x205.png 300w" sizes="(max-width: 616px) 100vw, 616px" /></p>



<p>The code for this field looks like below. Again, refer to the HTML and it should have this field already setup for you.</p>



<pre class="wp-block-code"><code lang="markup" class="language-markup">&lt;input type="file" name="attachment"></code></pre>



<p><strong>Important: </strong>You don&#8217;t need to create a column named &#8220;attachment&#8221; in the list. SharePoint allows an attachment to be tied up to each list item. This is a pretty cool feature.</p>



<h3 class="wp-block-heading">How do I install the plugin?</h3>



<p>Let&#8217;s begin by grabbing the files from <a href="https://github.com/michaelsoriano/sp-forms/archive/master.zip">Github</a>. Unzip the package, and upload to a document library in your SharePoint site. It will look something like below:</p>



<p><img decoding="async" width="666" height="443" class="alignnone size-full wp-image-6229" src="https://michaelsoriano.com/wp-content/uploads/2017/11/files-in-doclib.png" alt="files" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/files-in-doclib.png 666w, https://michaelsoriano.com/wp-content/uploads/2017/11/files-in-doclib-300x200.png 300w" sizes="(max-width: 666px) 100vw, 666px" /></p>



<p>On the Document Libary settings, click &#8220;Open in Explorer&#8221;.</p>



<p><img decoding="async" width="750" height="416" class="alignnone size-full wp-image-6263" src="https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-ie.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-ie.png 750w, https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-ie-300x166.png 300w" sizes="(max-width: 750px) 100vw, 750px" /></p>



<p>This will now open, as if it was a directory in your local drive. Let&#8217;s open the &#8220;<strong>sp-forms.html</strong>&#8221; with a text editor such as Notepad++.</p>



<p><img decoding="async" width="626" height="416" class="alignnone size-full wp-image-6264" src="https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-notepad.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-notepad.png 626w, https://michaelsoriano.com/wp-content/uploads/2017/11/open-in-notepad-300x199.png 300w" sizes="(max-width: 626px) 100vw, 626px" /></p>



<p>Edit the paths of the sp-forms.css and sp-forms.js to the directory that you added them to.</p>



<p>Then create a page in SharePoint, add a Content Editor Webpart:</p>



<p><img decoding="async" width="850" height="245" class="alignnone size-full wp-image-6261" src="https://michaelsoriano.com/wp-content/uploads/2017/11/add-cewp.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/add-cewp.png 850w, https://michaelsoriano.com/wp-content/uploads/2017/11/add-cewp-300x86.png 300w, https://michaelsoriano.com/wp-content/uploads/2017/11/add-cewp-768x221.png 768w" sizes="(max-width: 850px) 100vw, 850px" /><br></p>



<p>In the settings for that wepart, add the path to the HTML file in the document library.</p>



<p><img decoding="async" width="369" height="350" class="alignnone size-full wp-image-6233" src="https://michaelsoriano.com/wp-content/uploads/2017/11/map-to-html.png" alt="map to html" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/map-to-html.png 369w, https://michaelsoriano.com/wp-content/uploads/2017/11/map-to-html-300x285.png 300w" sizes="(max-width: 369px) 100vw, 369px" /></p>



<p>If it can&#8217;t find the list, you will see an error message like below:</p>



<p><img decoding="async" width="410" height="323" class="alignnone size-full wp-image-6228" src="https://michaelsoriano.com/wp-content/uploads/2017/11/error-message.png" alt="error message" srcset="https://michaelsoriano.com/wp-content/uploads/2017/11/error-message.png 410w, https://michaelsoriano.com/wp-content/uploads/2017/11/error-message-300x236.png 300w" sizes="(max-width: 410px) 100vw, 410px" /></p>



<p>That means that you should create the list, along with the columns that is described in the beginning of this tutorial.</p>
<p>The post <a href="https://michaelsoriano.com/sharepoint-forms-custom-html/">Create Custom HTML Forms for SharePoint with this jQuery Plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/sharepoint-forms-custom-html/feed/</wfw:commentRss>
			<slash:comments>97</slash:comments>
		
		
			</item>
		<item>
		<title>Working with jQuery&#8217;s AJAX, Promises and Deferred objects</title>
		<link>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/</link>
					<comments>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 11 Feb 2017 21:17:12 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6022</guid>

					<description><![CDATA[<p>jQuery&#8217;s implementation of making AJAX calls is quite easy to understand. There is $.ajax(), $.get(), $getJSON(), $.post() &#8211; which are all xhr requests, just different ways of writing it. It probably has the most straightforward syntax available and that&#8217;s why developers continue to use it, more than other libraries.The funny thing is, once we get [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with jQuery&#8217;s AJAX, Promises and Deferred objects</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>jQuery&#8217;s implementation of making AJAX calls is quite easy to understand. There is <em>$.ajax(), $.get(), $getJSON(), $.post()</em> &#8211; which are all xhr requests, just different ways of writing it. It probably has the most straightforward syntax available and that&#8217;s why developers continue to use it, more than other libraries.<br><img decoding="async" width="700" height="200" class="alignnone size-full wp-image-6042" src="https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax.png" alt="" srcset="https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax.png 700w, https://michaelsoriano.com/wp-content/uploads/2017/02/jquery-ajax-300x86.png 300w" sizes="(max-width: 700px) 100vw, 700px" /><br>The funny thing is, once we get to know it, we almost want to do everything via AJAX. From fetching and posting data to grabbing static files and compiling templates, &#8211; you name it. Before you know it, we&#8217;re making AJAX calls all over the place. It can get ugly really fast. Without knowing Promises and Deferred, our code syntax will get messy.</p>



<p>For instance, you&#8217;ve probably run into this problem at one point.<br>Notice our &#8220;results&#8221; array is empty after we run our function:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   $.get('/page.php',function(data){
       console.log(data) //filled!
       return data;
   });
}
var results = getData();
console.log(results); //empty!
</code></pre>



<p>The issue here is our getData() method continues to run even before our AJAX call finishes. So naturally, our results will log empty. One thing we DON&#8217;T want to do is to continue our logic inside the <em>$.get()</em> utility!</p>



<h3 class="wp-block-heading">Enter Promises</h3>



<p>jQuery have promises implemented with their AJAX methods. In a nutshell, they are utilities that allow us to work with events that have completed or put them in queues or chain them &#8211; all of that good stuff.  In our case, we need a &#8220;<em>promise</em>&#8220;. This allows us to interact with our AJAX requests &#8211; well outside our <em>$.get()</em> utility. So we can continue with our logic as designed.</p>



<p>So let&#8217;s solve our issue with <strong>.done() </strong>&#8211; which is a method that comes with <em>$.get()</em>:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   return $.get('/page.php');
}
getData().done(function(data){
  console.log(results); //filled!
});</code></pre>



<p>As you can see, we can use our function getData() &#8211; anywhere in our code as we&#8217;ve intended it to be. Note that there is also <strong>.fail(), .always()&nbsp;</strong> &#8211; which are the other methods for our $.get() promise object. <em>.fail()</em> for &#8211; when our call fails, <em>.always()</em>&nbsp;occurs every time it runs. The syntax is very self-explanatory.<br>Now we can also do this:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">getData().fail(function(error){
  console.log(error); //some error handling
}).always(function(){
  //something that happens every time...
});</code></pre>



<p>Which may serve as a global error handler for our getData() function.</p>



<p>You can also do both!</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData (){
   var ajax = $.get('/page.php',function(data){
     //do something with data here
   });
   return ajax;
}
getData().done(function(data){
  //do something else with data here
});</code></pre>



<p>So our method getData() &#8211; will always run our success function inside <em>$.get()</em>, while we use <strong>.done() </strong>&#8211; everywhere else in our code.</p>



<h3 class="wp-block-heading">Multiple AJAX calls</h3>



<p>What about multiple (different)&nbsp;AJAX calls? Something like below:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
getData1().done(function(data){
  //do something here
});
getData2().done(function(data){
  //do something here
});
getData3().done(function(data){
  //do something here
});</code></pre>



<p>This is fine, but it looks rather clumsy don&#8217;t you think. There is a method called <strong>.when() </strong>&#8211; which deals with stuff like this.</p>



<p>Instead of writing multiple <strong>.done(), </strong>we can elegantly compile them into a single block. We still get access to the same objects &#8211; as if we&#8217;re dealing with each AJAX call individually.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
$.when(getData1(),getData2(),getData3()).done(function(r1,r2,r3){
   console.log(r1) //[data, status, xhrObj]
   console.log(r2) //[data, status, xhrObj]
   console.log(r3) //[data, status, xhrObj]
})</code></pre>



<p>Note that each response returns an array. So for example you want to access the data of the first response, you do a <strong>r1[0]</strong> and so forth.</p>



<h3 class="wp-block-heading">Multiple <em>Dynamic</em> AJAX calls</h3>



<p>Now this one is tricky. It has been asked in <a href="http://stackoverflow.com/questions/19614354/dynamic-multiple-deferred-jquery-ajax-calls">StackOverflow</a> &#8211; which has an answer I would have not guessed. First thing is to get our requests in an array format. So this will be the dynamic part and it&#8217;s up to you how you want to design that. Now, <em>$.when</em> is smart enough to process the calls &#8211; if you pass them in single or an array.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">var requests = [ //this will be the dynamic part
  $.get('page1.php'),
  $.get('page2.php'),
  $.get('page3.php')
]
$.when.apply($,requests).done(function(){
  console.log(arguments); //array of responses [0][data, status, xhrObj],[1][data, status, xhrObj]...
})</code></pre>



<p>But note that we use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">.apply</a> after <em>$.when</em> This is so we can have access to a special variable called &#8220;arguments&#8221;. The arguments hold the responses from our array of calls, in a multi-dimensional array format.</p>



<p>As you can see, our promise is still in-tact and does it&#8217;s thing for dynamic AJAX calls.</p>



<h3 class="wp-block-heading">$.Deferred()</h3>



<p>As the method implies, <em>$.Deferred()</em> is to put in on hold, until you&#8217;re ready to interact with it. <em>$.Deferred()</em> is useful when we have actions such as multiple AJAX calls and we want to continue interacting with them at a later time.</p>



<p>Building on our example, let&#8217;s wrap our <em>$.when()</em> inside<b> </b>a function so we can call it later. Let&#8217;s use the <strong>.resolve()</strong> function of $.Deferred to illustrate:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function getData1 (){
   return $.get('/page1.php');
}
function getData2 (){
   return $.get('/page2.php');
}
function getData3 (){
   return $.get('/page3.php');
}
function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).done(function(){
     setTimeout(function(){
       def.resolve();
     },2000)
   })
   return def.promise();
}
defCalls();//returns the promise object</code></pre>



<p>You see that we are delaying our .resolve by 2 seconds using setTimeout(). You will see our def.promise() will take 2 seconds to return.</p>



<p>Also, now we have an accessible <em>defCalls()</em> promise object that we can use at a later time:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">defCalls().done(function(){
  //do something here
})</code></pre>



<p>You can also pass parameters&nbsp;to <em>.resolve() &#8211; </em>for later use in our defCalls() promise object. For example, the responses that came back from our call:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).done(function(r1,r2,r3){
     def.resolve(r1,r2,r3);
   })
   return def.promise();
}
defCalls().done(function(d1,d2,d3){
   //now we have access to data...
})</code></pre>



<p>What about multiple dynamic calls? We already learned about .apply(). We simply do the same thing so we can pass &#8220;arguments&#8221;:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   var requests = [
     getData1(),
     getData2()
   ]
   $.when.apply($,requests).done(function(){
     def.resolve(arguments);
   })
   return def.promise();
}
defCalls().done(function(arr){
   //now we have access to array of data
   console.log(arr);
})</code></pre>



<p>Lastly, let&#8217;s just say we want to create an action for failed events, we use the <strong>.reject()</strong> method for that:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript">function defCalls(){
   var def = $.Deferred();
   $.when(getData1(),getData2(),getData3()).fail(function(){
     def.reject();
   })
   return def.promise();
}
defCalls().fail(function(){
   //do something here
})</code></pre>



<p>As you can see, there many benefits in using promises and deferred objects &#8211; especially in asynchronous programming with jQuery&#8217;s AJAX. Not only that it will make your code easier to read. But it also makes it easier to debug, well factored and organized &#8211; the way jQuery intended it to be.</p>



<p>I would like to read comments on how you&#8217;re using these objects in your own code. Please leave them below.</p>
<p>The post <a href="https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/">Working with jQuery&#8217;s AJAX, Promises and Deferred objects</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/feed/</wfw:commentRss>
			<slash:comments>22</slash:comments>
		
		
			</item>
		<item>
		<title>Better handling for your HTML tables in Responsive view with this jQuery Plugin</title>
		<link>https://michaelsoriano.com/better-html-table-responsive-view-jquery-plugin/</link>
					<comments>https://michaelsoriano.com/better-html-table-responsive-view-jquery-plugin/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 12 Dec 2015 17:24:14 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery plugin]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4448</guid>

					<description><![CDATA[<p>So I had another challenge at my work. You see, we use plenty of SharePoint based sites, and a lot of the markup that it outputs is table based &#8211; especially the contents of a list. Now this is fine for tabular data and such &#8211; but in mobile view, it renders horribly. The rows [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/better-html-table-responsive-view-jquery-plugin/">Better handling for your HTML tables in Responsive view with this jQuery Plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>So I had another challenge at my work. You see, we use plenty of SharePoint based sites, and a lot of the markup that it outputs is table based &#8211; especially the contents of a list. Now this is fine for tabular data and such &#8211; but in mobile view, it renders horribly. The rows become too tall because of the contents getting smushed. Scollbars from left to right at the bottom of the screen.<br />
So I decided to write a jQuery plugin to alleviate this problem. It&#8217;s called it StackedRows.js.<br />
<a href="https://github.com/michaelsoriano/stacked-rows">View in Github</a><br />
<a href="http://demo.michaelsoriano.com/stacked-rows/">View Demo</a><br />
StackedRows basically goes through each of the rows in your table and creates a single row right below it &#8211; that&#8217;s only visible in mobile view. When the media query hits (you can set this up in the CSS), the ugly rows get hidden, and the mobile row displays &#8211; in a stacked vertical fashion. Hence &#8220;stacked rows&#8221;:<br />
<img decoding="async" class="alignnone size-full wp-image-5295" src="https://michaelsoriano.com/wp-content/uploads/2015/07/stacked-rows1.jpg" alt="stacked-rows1" width="693" height="915" srcset="https://michaelsoriano.com/wp-content/uploads/2015/07/stacked-rows1.jpg 693w, https://michaelsoriano.com/wp-content/uploads/2015/07/stacked-rows1-227x300.jpg 227w" sizes="(max-width: 693px) 100vw, 693px" /><br />
The responsive view of your table is much easier to digest in a mobile device. You can completely customize the look of each row with the stylesheet that it comes with. The best part is it still produces compliant HTML (even though it&#8217;s rendered on through Javascript).</p>
<h3>How to use:</h3>
<p>Just like a regular jQuery plugin, you need to have jQuery included in page to use. Then simply call inside a .ready() with your selectors and options included. An example is shown below:</p>
<pre>$(document).ready(function(){
   $('.table1').stackedRows();
})
</pre>
<h3>Options</h3>
<p>You can pass several options when calling the plugin. Check the table below for an explanation of how the options work.</p>
<table class="table table-bordered table-striped responsive-utilities" style="margin-top: 25px; margin-bottom: 30px;">
<thead>
<tr>
<th>Option</th>
<th>Type</th>
<th>Description</th>
<th class="hidden-xs">Default Value</th>
</tr>
</thead>
<tbody>
<tr>
<th><code>classPrefix</code></th>
<td class="is-visible">string</td>
<td>class prefix for CSS styling</td>
<td class="is-hidden hidden-xs">sr</td>
</tr>
<tr>
<th><code>firstRowHeader</code></th>
<td class="is-hidden">bool</td>
<td>does first row of table a heading?</td>
<td class="is-visible hidden-xs">true</td>
</tr>
<tr>
<th><code>showLabels</code></th>
<td class="is-hidden">bool</td>
<td>show labels (column names) in mobile?</td>
<td class="is-hidden hidden-xs">true</td>
</tr>
<tr>
<th><code>altRowStyle</code></th>
<td class="is-hidden">bool</td>
<td>add a class for alternating rows</td>
<td class="is-hidden hidden-xs">true</td>
</tr>
</tbody>
</table>
<p>The options are quite explanatory. The demo page also shows some of the options described above.</p>
<p>The post <a href="https://michaelsoriano.com/better-html-table-responsive-view-jquery-plugin/">Better handling for your HTML tables in Responsive view with this jQuery Plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/better-html-table-responsive-view-jquery-plugin/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to make a SharePoint List work with Bootstrap &#8211; using SPServices and jQuery</title>
		<link>https://michaelsoriano.com/sharepoint-bootstrap-using-spservices-and-jquery/</link>
					<comments>https://michaelsoriano.com/sharepoint-bootstrap-using-spservices-and-jquery/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 17 Jul 2015 16:23:46 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Bootstrap]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[SOAP]]></category>
		<category><![CDATA[SPServices]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4446</guid>

					<description><![CDATA[<p>For those of you who have worked with SharePoint in the past, particularly with lists, CEWPs (Content Editor Web Part) and front end code, then you probably know that these lists do not work well in mobile. The markup is just too messy &#8211; invalid tags, divs inside spans, inline Javascripts, inline styles and even [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/sharepoint-bootstrap-using-spservices-and-jquery/">How to make a SharePoint List work with Bootstrap &#8211; using SPServices and jQuery</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>For those of you who have worked with SharePoint in the past, particularly with lists, CEWPs (<a href="https://support.office.com/en-ca/article/Content-Editor-Web-Part-c1350ff6-934c-4c2e-8e53-1ec3b548a0dc">Content Editor Web Part</a>) and front end code, then you probably know that these lists do not work well in mobile. The markup is just too messy &#8211; invalid tags, divs inside spans, inline Javascripts, inline styles and even tables! So it&#8217;s no surprise that making SharePoint work with Bootstrap is not an easy task.</p>
<h5>Note that this plugin will require the following files:</h5>
<ul>
<li>jquery.min.js</li>
<li>jquery.SPServices-2014.02.min.js</li>
<li>bootstrap.min.css</li>
</ul>
<p>In this post, I will show you how to use a Javascript plugin that I&#8217;ve written to basically recreate the markup of these SP lists so it works with Bootstrap / Mobile. It also has extra functionality like paging, filters, expand/collapse and other options. By the time we&#8217;re done, your list will look real good in desktop, tablet and mobile view:<br />
<a href="https://github.com/michaelsoriano/sp-bootstrap-list-viewer">View in Github</a></p>
<h3>How to use the Plugin:</h3>
<p>Note that I&#8217;ve only tested this with SharePoint 2013. You may need administrator rights to your website, as well as you should know how to work with custom lists and document libraries and such.<br />
After you have downloaded the files, open the &#8220;sp-bootstrap-list-viewer.html&#8221; in you text editor. This is where you will add the plugin information.<br />
You have to change the CHANGE-TO-YOUR-PATH in the JavaScript and CSS inclusion &#8211; to your downloaded path.<br />
Then, you add 2 things: the list name, the &#8220;Answer&#8221; column. The rest of the options are optional such as the &#8220;filterBy&#8221; and &#8220;rowLimit&#8221;. The table below will show you want the rest of the options do.<br />
<img decoding="async" class="alignnone size-full" src="https://michaelsoriano.com/wp-content/uploads/2015/07/sp-list3.jpg" alt="sp-list1" width="412" height="358" /><br />
Once you have edited the html file, upload it to a location in your SharePoint site, typically a document library. You will need to copy the location of the file.<br />
<img decoding="async" class="alignnone size-full" src="https://michaelsoriano.com/wp-content/uploads/2015/07/sp-list2.jpg" alt="sp-list1" width="412" height="358" /><br />
Let&#8217;s go ahead and add a CEWP into your SharePoint page. in the &#8220;Content Link&#8221; input, add the location of the html file you&#8217;ve just uploaded.<br />
<img decoding="async" class="alignnone size-full" src="https://michaelsoriano.com/wp-content/uploads/2015/07/sp-list1.jpg" alt="sp-list1" width="412" height="358" /><br />
Click &#8220;OK&#8221; and if everything is configured correctly, you should see the plugin do its thing:<br />
<img decoding="async" class="alignnone size-full wp-image-4447 noborder" src="https://michaelsoriano.com/wp-content/uploads/2015/07/sp-bootstrap-list-viewer.gif" alt="sp-bootstrap-list-viewer" width="787" height="520" /><br />
The table below contains the options for the plugin and an explanation of what they&#8217;re for:</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Option name</th>
<th>Default Value</th>
<th>Required?</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">instance</th>
<td>Random Value</td>
<td>Yes</td>
<td>Used as the &#8220;Id&#8221; of your plugin</td>
</tr>
<tr>
<th scope="row">listName</th>
<td>none</td>
<td>Yes</td>
<td>Name of the SP list</td>
</tr>
<tr>
<th scope="row">question</th>
<td>Title</td>
<td>Yes</td>
<td>Title of the row</td>
</tr>
<tr>
<th scope="row">answer</th>
<td>none</td>
<td>Yes</td>
<td>Body of the row</td>
</tr>
<tr>
<th scope="row">filterBy</th>
<td>none</td>
<td>No</td>
<td>Category column to filter rows</td>
</tr>
<tr>
<th scope="row">rowLimit</th>
<td>5</td>
<td>No</td>
<td>Number of rows to show</td>
</tr>
</tbody>
</table>
<p>One thing to remember. If you plan to use the plugin multiple times in a page, you need to change the &#8220;instance&#8221; value to a random number prefixed with alphanumeric characters. You also need to make this the &#8220;Object&#8221; name of your html (where it says var <strong>spBL233565656</strong> = new spBootstrapList &#8230;). This will make the instances of your plugin unique in every page and will not clash with each other.</p>
<h3>Under the hood:</h3>
<p>For those of you who want to know more about how the plugin works, I will show you some of it&#8217;s main functionality. Note that this was originally built for a FAQ list for SharePoint, hence the FAQ names such as &#8220;Question&#8221; and &#8220;Answer&#8221;. Though the plugin will work with any kind of SP list.</p>
<h6>Requirements</h6>
<p>We will need some help with Mark Anderson&#8217;s <a href="https://github.com/sympmarc/SPServices">SPServices</a> &#8211; a jQuery plugin that basically does the web service calls for us. This allows us to work with the lists&#8217; data and convert it to our desired markup. Of course we will need <a href="http://getbootstrap.com/">Bootstrap </a>&#8211; which will take care of the responsive and overall styles, as well as <a href="https://jquery.com/">jQuery</a> for DOM manipulation.<br />
Notice the required scripts and styles. You can link to them externally or download them to a document library in SharePoint. Our constructor spBootstrapList() calls our Javascript class, passing along our required arguments. Again, the variable name &#8220;spBL233565656&#8221; and the value for &#8220;instance&#8221; has to be identical. This is for using it multiple of these in a single page.<br />
So going into the Javascript plugin: <strong>sp-bootstrap-list-viewer.js</strong>, you will see that on first load there&#8217;s a public method that gets called to set things up &#8220;init()&#8221;. This makes the initial call to the plugin &#8220;SPServices&#8221;. As I&#8217;ve mentioned, the plugin does the AJAX call to the SharePoint web service. It uses SOAP as its protocol so the request / response will be in XML format. Our init() method also checks for valid fields:</p>
<pre class="">var init = function(){
var ajax = methods.callSPServices(_settings.rowLimit, true);
$(ajax.responseXML).SPFilterNode("z:row").each(function(e) {
    var errors = Array();
    if(typeof $(this).attr('ows_' + _settings.question) == 'undefined'){
        errors.push("Invalid field name for Question: " + _settings.question);
    }
    if(typeof $(this).attr('ows_' + _settings.answer) == 'undefined'){
        errors.push("Invalid field name for Answer: " + _settings.answer);
    }
    if(_settings.filterBy !== '') {
        if(typeof $(this).attr('ows_' + _settings.filterBy) == 'undefined'){
            errors.push("Invalid field name for FilterBy: " + _settings.filterBy);
        }
    }
    _errors = errors;
    methods.parseResponse($(this));
});
</pre>
<p>Then we parse our response and we fill our internal object &#8220;_faqs&#8221;: Notice the SharePoint internal list names that start with &#8220;ows_&#8221; &#8211; these are how it comes out of the <a href="https://developers.google.com/doubleclick-publishers/docs/soap_xml">SOAP response</a>. We parse it to our own object with more meaningful keys and it&#8217;s values:</p>
<pre>parseResponse : function(resp){
    var record = {};
    record.question = resp.attr('ows_' + _settings.question);
    record.answer = resp.attr('ows_' + _settings.answer);
    record.created = resp.attr('ows_' + 'Created');
    if(_settings.filterBy !== ''){
        record.filterBy = resp.attr('ows_' + _settings.filterBy);
    }
    _faqs.push(record);
},
</pre>
<p>By the way, in order for us to make public methods from within our plugin is that we assign it to the &#8220;this&#8221; keyword. This way it becomes accessible from the outside. Here is an example of all the public methods of our plugin:</p>
<pre>this.paginate = paginate;
this.filter = filter;
this.showHideFilters = showHideFilters;
this.clearFilter = clearFilter;
this.showHideAnswer = showHideAnswer;
</pre>
<p>Continuing with our process, note that we need the &#8220;_faq&#8221; array to be filled for our next method to fire. This method is called <strong>methods.buildFaqs()</strong>, So we built another object called &#8220;methods&#8221; and inside this is a series of functions. This will be our &#8220;internal&#8221; methods.<br />
If you look at the buildFaqs() method, the code looks like below:</p>
<pre class="">buildFaqs : function(){
  var output = '';
  for(var i=0; i&lt;_faqs.length; i++){
    var hr = (i != (_faqs.length-1)) ? '</pre>
<p><em>[code above has been truncated &#8211; due to syntax highlighting error]</em><br />
So you see, we have our SharePoint list data in our array, and we build the HTML from it.</p>
<h6>Pagination</h6>
<p>Our pagination logic is quite interesting. We use the Bootstrap pagination HTML, and for each page, we need to do a <a href="http://www.w3schools.com/ajax/">AJAX</a> call in order to get the next page ID. This is how SharePoint determines where to offset the record when a query is made by using &#8220;<a href="https://social.msdn.microsoft.com/Forums/en-US/02663336-3185-498a-904f-86845106b624/getlistitems-with-jquery-using-listitemcollectionpositionnext-as-a-query-option?forum=sharepointdevelopmentprevious">ListItemCollectionPositionNext</a>&#8221; as a parameter.</p>
<pre>var buildPagination = function(){
  if(_errors.length &gt; 0) {
      $('#'+ _settings.instance+' .spBLPagerContainer').html('');
      console.log('Exiting buildPagination()');
      return false;
  }
  methods.getTotal(); //inside here we build filters
  if(parseInt(_totalRecords) &gt; parseInt(_settings.rowLimit)) { //yes paginate
      var pages = Math.ceil(_totalRecords / _settings.rowLimit);
      var positions = Array('');
      for (var i=0; i &lt; (pages - 1); i++) { //builds the values required 'ListItemCollectionPositionNext'
          var pos = '';
          if(i == 0){ //skips first to not pass pos
              positions.push(methods.getNextPos(pos));
          }else{
              var offset = i;
              positions.push(methods.getNextPos(positions[offset]));
          }
      }
  // console.log(positions);
  methods.buildPagination(positions);
  }else{ // no need to paginate
      $('#'+ _settings.instance+' .spBLPagerContainer').html('');
  }
}
</pre>
<p>We then proceed to build the actual markup with our internal method: methods.buildPagination():</p>
<pre class="">buildPagination : function(items){
  if(_firstLoad == false){
      $('#'+ _settings.instance+' .spBLPagerContainer').html(pager);
  }
  _positions = items;
  var pager = '</pre>
<p>&nbsp;<br />
<em>[code above has been truncated &#8211; due to syntax highlighting error]</em><br />
Each button has an inline &#8220;onclick&#8221; that calls our public &#8220;paginate()&#8221; method. Each of them also has the attribute &#8220;data-position&#8221; which holds the offset &#8220;ID&#8221; that we talked about:</p>
<pre>var paginate = function(clicked){
  if($(clicked).parents('li').hasClass('active') || $(clicked).parents('li').hasClass('disabled')){
      return false;
  }
  $('#'+ _settings.instance+' .pagination li').removeClass('active');
  var pos = $(clicked).attr('data-position') != '' ? $(clicked).attr('data-position') : '';
  if($(clicked).hasClass('NextButton')){
      $('#'+ _settings.instance+' a[data-position="'+pos+'"]').not('.NextButton').parents('li').addClass('active');
  }else if($(clicked).hasClass('PrevBtn')){
      $('#'+ _settings.instance+' a[data-position="'+pos+'"]').not('.PrevBtn').parents('li').addClass('active');
  }else{
      $(clicked).parents('li').addClass('active');
  }
  methods.updateNextPrevBtns(pos);
  methods.clearFaqs();
  var options = {
      CAMLViewFields: methods.fieldsToRead(true),
      CAMLQuery: methods.query(),
      CAMLRowLimit : _settings.rowLimit,
      CAMLQueryOptions: ""
  }
  var ajax = $().SPServices(methods.mergeSPCommon(options));
  $(ajax.responseXML).SPFilterNode("z:row").each(function(e) {
      methods.parseResponse($(this));
  });
  methods.buildFaqs();
}
</pre>
<p>You noticed too from the code above that we use SPServices on each click. That&#8217;s because we are only grabbing a predefined set of records &#8211; which is the limit that we pass into our plugin.</p>
<h6>Filters</h6>
<p>So the plugin supports filtering. This means that you can choose a field from your list and make that a &#8220;filter&#8221; column.<br />
First, assuming you&#8217;ve selected a valid field, we have to build it. Take a look at the code below:</p>
<pre>getFilterByValues : function(resp){
  var filterList = Array();
  var filterListUnique = Array();
  $(resp.responseXML).SPFilterNode("z:row").each(function(e) {
      var filterValue = $(this).attr('ows_' + _settings.filterBy);
          if(typeof filterValue !== 'undefined'){ //only add to array if theres a value
              filterList.push(filterValue);
          }
  });
  $.each(filterList,function(i,el){ //get rid of duplicates
      if($.inArray(el, filterListUnique) === -1){
          filterListUnique.push(el);
      }
  });
  _filterByListUnique = filterListUnique;
  _filterByList = filterList;
}
</pre>
<p>The above simply grabs the data. And since there are duplicate entries &#8211; we will have to make them unique and fill up our &#8220;_filterByListUnique&#8221; array. This is next:</p>
<pre class="">buildFilters : function(){
  var count = 0;
  var out = '';
  out +=</pre>
<p><em>[code above has been truncated &#8211; due to syntax highlighting error]</em><br />
The above builds out the checkboxes we need for our filtering capabilities. Now when each item is clicked, it triggers our filter() method:</p>
<pre>var filter = function(clicked){
  _firstLoad = false;
  _filterByValues = [];
  $('#'+ _settings.instance+'-filtersArray :checkbox:checked').each(function(e){
      _filterByValues.push($(this).val());
  })
  methods.filter();
}
</pre>
<p>Which actually calls our internal methods.filter() method:</p>
<pre>filter : function(){
  $('#'+ _settings.instance+'-filtersArray input').attr('disabled', 'disabled');
  $('#'+ _settings.instance+' .clearFilter').attr('disabled', 'disabled');
  methods.clearFaqs();
  var ajax = methods.callSPServices(_settings.rowLimit, true);
  $(ajax.responseXML).SPFilterNode("z:row").each(function(e) {
      methods.parseResponse($(this));
  });
  setTimeout(function(){
      methods.buildFaqs();
      buildPagination();
      $('#'+ _settings.instance+'-filtersArray input').removeAttr('disabled');
      $('#'+ _settings.instance+' .clearFilter').removeAttr('disabled');
  },10);
  if(_filterByValues.length &gt; 0){
      $('#'+ _settings.instance + ' .clearFilter').show();
  }else{
      $('#'+ _settings.instance + ' .clearFilter').hide();
  }
}
</pre>
<p>A lot going on here. You see that we make a new AJAX call through SPServices, passing our filter value. We parse the response, rebuild our items through &#8220;methods.buildFaqs()&#8221; and rebuild our pagination through buildPagination().<br />
There&#8217;s much more logic in the plugin such as the creating the <a href="https://msdn.microsoft.com/en-us/library/dd588092%28v=office.11%29.aspx">CAML</a> queries &#8211; but I decided not to go through them. If you&#8217;re well versed with .NET and SharePoint &#8211; you will be able to decipher these easy.</p>
<h3>Console Debugging</h3>
<p>Once you have the code in place &#8211; save and refresh your page. If by any reason some of the options are passed incorrectly, error handling is added and will be displayed in the HTML. You also need to turn on the console for more messages of what&#8217;s going on. I&#8217;ve added a couple of helpers that will get you information about your list such as getAllColumns(). This will display all of the fields that belong to the list you&#8217;re working with. Simply use the instance name + getAllColumns().</p>
<h3>Conclusion</h3>
<p>As you can see, we can make SharePoint internal lists work responsively. We may have to redo the markup entirely &#8211; but there are web services in place to grab the data. Thanks to open source code such as SPServices, jQuery and Bootstrap &#8211; our task becomes somewhat easier.<br />
Feel free to comment below.</p>
<p>The post <a href="https://michaelsoriano.com/sharepoint-bootstrap-using-spservices-and-jquery/">How to make a SharePoint List work with Bootstrap &#8211; using SPServices and jQuery</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/sharepoint-bootstrap-using-spservices-and-jquery/feed/</wfw:commentRss>
			<slash:comments>56</slash:comments>
		
		
			</item>
		<item>
		<title>How to do Ajax form validation with inline error messages &#8211; without using a plugin</title>
		<link>https://michaelsoriano.com/how-to-ajax-validate-forms/</link>
					<comments>https://michaelsoriano.com/how-to-ajax-validate-forms/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 14 Mar 2015 17:39:05 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[form validation]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4386</guid>

					<description><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>When in comes to validating forms, there are basically two techniques you can use: 1) Server-side validation and 2) Client-side validation. Server-side validation is when form data is submitted, server analyzes then returns the user back to the form when items are invalid. Client-side on the other hand, is when Javascript analyses the fields before actually submitting the data to the server.<br />
<strong>Update 4/2/2016:</strong> &#8211; The code below is not meant to be a &#8220;copy and paste&#8221; type of thing. You will need some PHP and Javascript debugging experience to successfully integrate into your project.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-inline-errors.gif" alt="ajax-inline-errors" width="471" height="282" class="alignnone size-full wp-image-4387" /><br />
Plenty argue (including myself), that server side validation is more secure. This is because client side validation can be manipulated (or simply turned off). But the bad thing about server side validation &#8211; is you see the page refresh. This is considered to be <a href="http://fearlessflyer.com/10-common-ui-mistakes-and-how-to-avoid-them/">bad user experience</a> &#8211; especially in mobile.<br />
I&#8217;ve seen solutions where they use both server side and client side &#8211; with validation rules in Javascript and their server language. But that&#8217;s a bit redundant isn&#8217;t it? Plus think of the maintenance of code that you have to do. Wouldn&#8217;t it be nice to combine both?</p>
<h3>Combining both techniques</h3>
<p>What we&#8217;re trying to achieve is have the security of server side validation, the elegance of displaying the errors inline, as well as have a fall back behavior. So even when users turn off Javascript &#8211; you will see the same error messages. Oh and of course, we will also have the good user experience of the page not refreshing when there&#8217;s errors.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors2.jpg" alt="ajax-errors2" width="643" height="377" class="alignnone size-full noborder wp-image-4388" /><br />
Keep in mind that you will need a bit of programming know how &#8211; especially in PHP and Javascript. Ready to get started? Let&#8217;s begin.</p>
<h3>The Markup</h3>
<p>We start with a regular form. The submit action would be a processing page where our server side logic will take place. You can also have the processing page the same as the page where the form is. But I like to keep files separate. Copy the code below into your HTML:</p>
<pre>
<form  action="process.php" method="post">
  <label>First Name</label>
  <input name="first_name" type="text"  />
  <label>Email</label>
  <input name="email" type="text"  />
  <input type="submit" value="Submit" />
</form>
</pre>
<p>Nothing fancy here. Just a regular form and a couple of fields. Remember to make your field names unique &#8211; for this is what we&#8217;ll use to validate our form.</p>
<h3>The Processing Page</h3>
<p>So when our form submits, it passes the $_POST array to this page. If you&#8217;re new to validating forms, the code below simply goes through the array and checks it against our rules for each field. Note that in our case &#8211; I&#8217;m simply checking if first name and email is empty. Of course in the real world, you will have to check for valid email and such.</p>
<pre>
session_start();
if(isset($_POST)){
  	if (empty($_POST['first_name'])) {
		$_SESSION['errors'][‘first_name'] = ‘First name is missing’;
        	}
	if (empty($_POST[‘email’])) {
		$_SESSION['errors'][‘email'] = ‘email is missing’;
        	}
        if(count($_SESSION['errors']) > 0){
	    //This is for ajax requests:
            if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                echo json_encode($_SESSION['errors']);
                exit;
             }
	    //This is when Javascript is turned off:
           echo “<ul>”;
           foreach($_SESSION['errors'] as $key => $value){
	      echo “<li>” . $value . “</li>”;
           }
           echo “</ul>”;exit;
    }else{
	//form validation successful - process data here!!!!
   }
}
</pre>
<p>The key to the code above is the check for an Ajax request. Notice the json_encode() method. This is when it&#8217;s an Ajax request and we simply echo our error array in JSON format. We will need this to format our inline messages later. The rest of the code is simply handled as if it&#8217;s regular server side processing.<br />
Again, notice the part where if it&#8217;s NOT an Ajax request &#8211; we simply echo out a list of our validation errors. You would probably want to style this better, or even echo it out in the same page as the form. But for the sake of our tutorial, I want to make it short and concise.</p>
<h3>Our Javascript</h3>
<p>I prefer to write jQuery, so the code below will only work if jQuery is included. The code below is to be added to our form page:</p>
<pre>
var data = {};
$(document).ready(function() {
  $('input[type="submit"]').on('click', function() {
      resetErrors();
      var url = 'process.php';
      $.each($('form input, form select'), function(i, v) {
          if (v.type !== 'submit') {
              data[v.name] = v.value;
          }
      }); //end each
      $.ajax({
          dataType: 'json',
          type: 'POST',
          url: url,
          data: data,
          success: function(resp) {
              if (resp === true) {
                  	//successful validation
                      $('form').submit();
                  	return false;
              } else {
                  $.each(resp, function(i, v) {
	        console.log(i + " => " + v); // view in console for error messages
                      var msg = '<label class="error" for="'+i+'">'+v+'</label>';
                      $('input[name="' + i + '"], select[name="' + i + '"]').addClass('inputTxtError').after(msg);
                  });
                  var keys = Object.keys(resp);
                  $('input[name="'+keys[0]+'"]').focus();
              }
              return false;
          },
          error: function() {
              console.log('there was a problem checking the fields');
          }
      });
      return false;
  });
});
function resetErrors() {
    $('form input, form select').removeClass('inputTxtError');
    $('label.error').remove();
}
</pre>
<p>Plenty of things going on above. Of course everything is wrapped inside our document.ready() handler, then we put a .click() for our submit button. So every time we click the submit button, we go through each field in the form and create a data object. This object contains the field names and their respective values (you can also use jQuery&#8217;s .serialize() for this purpose).<br />
We make an Ajax call to our processing page &#8211; where it does the validation in our PHP code previously. Now, remember our server side will echo a JSON object with our field names and error messages? We simply handle this by adding an error class and adding a &#8220;label&#8221; with the message through jQuery&#8217;s .after() function.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/ajax-errors4.jpg" alt="ajax-errors4" width="746" height="327" class="alignnone size-full wp-image-4390" /><br />
Of course, if there&#8217;s no errors &#8211; the form does a hard .submit() &#8211; to the same processing page and handled accordingly.</p>
<h3>Our CSS</h3>
<p>Of course, we have add our styling so our field will look like our screenshots above. Simply add this code inside style tags.</p>
<pre>
.error {
   color: #ff0000;
   font-size: 12px;
   margin-top: 5px;
   margin-bottom: 0;
}
.inputTxtError {
   border: 1px solid #ff0000;
   color: #0e0e0e;
}
</pre>
<p>Again, the styles are real basic and you probably want to do better in your own forms.</p>
<h3>Conclusion</h3>
<p>So there you have it. We&#8217;ve combined best of both worlds: server side and client side validation in one solution (thanks to Ajax). Our code has clear separation and very manageable. If a field validation rule has to change &#8211; we only need to change it in one place: the server code. Also, our users will benefit from our friendly form &#8211; and the way it gracefully tells them when they&#8217;ve missed a field and such.<br />
Let me know your thoughts and if you think this solution is a good fit for your projects. </p>
<p>The post <a href="https://michaelsoriano.com/how-to-ajax-validate-forms/">How to do Ajax form validation with inline error messages &#8211; without using a plugin</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-ajax-validate-forms/feed/</wfw:commentRss>
			<slash:comments>40</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s create a jQuery Plugin that checks user&#8217;s age when visiting your site.</title>
		<link>https://michaelsoriano.com/jquery-plugin-check-user-age/</link>
					<comments>https://michaelsoriano.com/jquery-plugin-check-user-age/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sun, 08 Mar 2015 07:56:16 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=4377</guid>

					<description><![CDATA[<p>As I was building my client&#8217;s new Vodka site, one of the requirements was a prompt that will ask the viewer for their date of birth. Seems simple enough right? So I started coding. Turns out that it takes a bit of work! There&#8217;s form validation, date logic, styling &#8211; so I decided to make [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/jquery-plugin-check-user-age/">Let&#8217;s create a jQuery Plugin that checks user&#8217;s age when visiting your site.</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>As I was building my client&#8217;s new Vodka site, one of the requirements was a prompt that will ask the viewer for their date of birth. Seems simple enough right? So I started coding. Turns out that it takes a bit of work! There&#8217;s form validation, date logic, styling &#8211; so I decided to make a plugin out of it. I&#8217;m going to call it: <a href="https://github.com/michaelsoriano/age-check">AgeCheck.js</a>.<br />
<a href="http://rawgit.com/fearlessflyer/age-check/master/index.html" rel="nofollow" class="viewdemo">View Demo</a><br />
<a class="" href="https://github.com/michaelsoriano/age-check" target="_blank" rel="noopener">View in Github</a><br />
I anticipate plenty of developers will need this kind of functionality. Now all they have to do is add a couple lines of code &#8211; and voila! Ready to start? Let&#8217;s begin.<br />
<img decoding="async" src="https://michaelsoriano.com/wp-content/uploads/2015/03/age-check-demo1.gif" alt="age-check-demo" width="640" height="353" class="alignnone size-full wp-image-4383" /></p>
<h3>Setting up the plugin:</h3>
<p>The code below sets up our plugin code. Basically it allows us to use the function name &#8220;ageCheck&#8221; and pass in an object (options) as parameters we can use inside our plugin.</p>
<pre>
(function ($){
    $.ageCheck = function(options) {
      //our code goes here...
     };
})(jQuery);
</pre>
<p>We then worry about what options we will allow our users to have. I suspect the minimum age will vary, they may want to have a &#8220;redirect&#8221; url, the &#8220;title&#8221; of the popup would be nice and the copy should be changeable as well.</p>
<pre>
var settings = $.extend({
    minAge : 21,
    redirectTo : '',
    title : 'Age Verification',
    copy : 'This Website requires you to be [21] years or older to enter. Please enter your Date of Birth in the fields below in order to continue:'
}, options);
</pre>
<p>The settings variable is using <a href="http://api.jquery.com/jquery.extend/">.extend()</a> &#8211; which merges our options and our internal object together &#8211; allowing it to be accessible throughout our plugin code.</p>
<h3>The Heart of our plugin</h3>
<p>Plenty of times when writing code &#8211; I find myself re-factoring code so it&#8217;s easier to digest. The main logic of the program I put in an internal variable called &#8220;_this&#8221;. This is not accessible anywhere but inside the plugin code itself. It contains all of the variables and methods we need for our plugin to work.<br />
The code below is our main object:</p>
<pre>
var _this = {
    month : '',
    day : '',
    year : '',
    age : '',
    errors : Array(),
    setValues : function(){
        var month = $('.month').val();
        var day = $('.day').val()
        _this.month = month;
        _this.day = day.replace(/^0+/, ''); //remove leading zero
        _this.year = $('.year').val();
    },
    validate : function(){
        _this.errors = [];
        if (/^([0-9]|[12]d|3[0-1])$/.test(_this.day) === false) {
            _this.errors.push('Day is invalid or empty');
        };
        if (/^(19|20)d{2}$/.test(_this.year) === false) {
            _this.errors.push('Year is invalid or empty');
        };
        _this.clearErrors();
        _this.displayErrors();
        return _this.errors.length < 1;
    },
    clearErrors : function(){
        $('.errors').html('');
    },
    displayErrors : function(){
        var html = '<ul>';
        for (var i = 0; i < _this.errors.length; i++) {
            html += '<li><span>x</span>' + _this.errors[i] + '</li>';
        }
        html += '</ul>';
        setTimeout(function(){$('.errors').html(html)},200);
    },
    reCenter : function (b){
        b.css("top", Math.max(0, (($(window).height() - (b.outerHeight() + 150)) / 2) +
                                    $(window).scrollTop()) + "px");
        b.css("left", Math.max(0, (($(window).width() - b.outerWidth()) / 2) +
                                    $(window).scrollLeft()) + "px");
    },
    buildHtml : function(){
        var copy = settings.copy;
        var months = ['January',
                      'February',
                      'March',
                      'April',
                      'May',
                      'June',
                      'July',
                      'August',
                      'September',
                      'October',
                      'November',
                      'December'];
        var html = '';
        html += '<div class="ac-overlay"></div>';
        html += '<div class="ac-container">';
        html += '<h2>' + settings.title + '</h2>';
        html += '<p>' + copy.replace('[21]','<strong>';
        html += settings.minAge+'</strong>'); + '</p>';
        html += '<div class="errors"></div>';
        html += '<div class="fields"><select class="month">';
        for(var i=0;i<months.length;i++){
            html += '<option value="'+i+'">'+months[i]+'</option>'
        }
        html += '</select>';
        html += '<input class="day" maxlength="2" placeholder="01" />';
        html += '<input class="year" maxlength="4" placeholder="1989"/>';
        html += '<button>Submit</button></div></div>';
        $('body').append(html);
        $('.ac-overlay').animate({
            opacity: 0.8
        }, 500, function() {
            _this.reCenter($('.ac-container'));
            $('.ac-container').css({opacity: 1})
        });
        $(".ac-container .day, .ac-container .year").focus(function(){
           $(this).removeAttr('placeholder');
        });
    },
    setAge : function(){
        _this.age = '';
        var birthday = new Date(_this.year, _this.month, _this.day);
        var ageDifMs = Date.now() - birthday.getTime();
        var ageDate = new Date(ageDifMs); // miliseconds from epoch
        _this.age = Math.abs(ageDate.getUTCFullYear() - 1970);
    },
    setSessionStorage  : function(key, val){
        try {
            sessionStorage.setItem(key,val);
            return true;
        } catch (e) {
            return false;
        }
    },
    handleSuccess : function(){
        var successMsg = '<h3>Success!</h3>';
        successMsg += '<p>You are now being redirected back to the application...</p>';
        $('.ac-container').html(successMsg);
        setTimeout(function(){
            $('.ac-container').animate({'top':'-350px'},200, function(){
                 $('.ac-overlay').animate({'opacity':'0'},500, function(){
                    if (settings.redirectTo != '') {
                        window.location.replace(settings.redirectTo);
                    }else{
                        $('.ac-overlay, .ac-container').remove();
                    }
                 });
            });
        },2000);
    }
}; //end _this
</pre>
<p>Our object contains everything form validation, re-centering the display, clearing errors, error and success handling and finally building the html. You can easily tell which part is which &#8211; by the names I have given the methods. This makes it easy for any programmer to come in and maintain the code.<br />
Now that we have our settings and the main logic &#8211; it&#8217;s time to execute our code.</p>
<h3>Chunks of Events</h3>
<p>So first, let&#8217;s check if there&#8217;s a flag that user is old enough. If you look in our main object, we&#8217;re setting a flag if user passes our age check. We called it &#8220;ageVerified&#8221; and set it to &#8220;true&#8221;. If they are, we don&#8217;t even show the box &#8211; we just let them in the site.</p>
<pre>
if(sessionStorage.getItem("ageVerified") == "true"){
    return false;
}
_this.buildHtml();
</pre>
<p>If the flag isn&#8217;t there, we continue with our popup using our buildHtml() method.<br />
Then the action begins when the click on our button. Below simply ties our methods to a &#8220;if, else&#8221; wrappers such as below:</p>
<pre>
$('.ac-container button').on('click', function(){
    _this.setValues();
    if (_this.validate() === true) {
        _this.setAge();
        if(_this.age >= settings.minAge){
            if(!_this.setSessionStorage("ageVerified", "true")){
                console.log('sessionStorage not supported by your browser');
            };
            _this.handleSuccess();
        }else{
            _this.errors.push('You are not old enough');
            _this.displayErrors();
        }
    }
});
</pre>
<p>So to explain, when a user click on our button &#8211; we set the values that are coming from the drop down and input fields in our form. It checks if they&#8217;re valid inputs &#8211; it they are &#8211; it sets the age we use in our plugin. Now there&#8217;s only 2 possible scenarios we set &#8211; if user is old enough or not. We handle both scenarios with letting them through or showing error messages.</p>
<h3>Some Styles</h3>
<p>Our plugin has to look nice. On top of that, we also don&#8217;t want it to clash with other styles of the site. We prefix all of our styles with the &#8220;ac-&#8221; to namespace our plugin classes.<br />
The CSS for our box is right below:</p>
<pre>
@import url(http://fonts.googleapis.com/css?family=Bree+Serif);
.ac-overlay{
    box-sizing: border-box;
    height:100%;
    width:100%;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99998;
    opacity:0;
	cursor: wait;
}
.ac-container {
    box-sizing: border-box;
    font-family: 'Bree Serif', serif;
    width: 360px;
    position: fixed;
    padding: 20px 20px 30px 20px;
    background: #fff;
    z-index: 99999;
    opacity:0;
    text-align:center;
    border-radius: 4px;
    box-shadow:0px 0px 5px #000;
    font-weight:normal;
}
.ac-container h2 {
    box-sizing: border-box;
    margin:0 0 14px 0;
    font-size:26px;
    border-bottom:1px dashed #ccc;
    padding-bottom:11px;
}
.ac-container h3 {
    box-sizing: border-box;
    color:#649D09;
    margin-bottom:5px;
    margin-top:15px;
    font-size:26px;
}
.ac-container p {
    box-sizing: border-box;
    margin:0 0 20px 0;
    font-size: 14px;
    color:#959595;
    line-height: 20px;
}
.ac-container p strong {
    color:#FF1F1F;
}
.ac-container select,
.ac-container input {
    box-sizing: border-box;
    color:#555;
    padding: 5px 10px;
    font-size: 12px;
    line-height: 1.5;
    border-radius: 3px;
    margin-right:5px;
    border:1px solid #ccc;
}
.ac-container input.day{
    box-sizing: border-box;
    width:45px;
    height:28px;
}
.ac-container input.year{
    box-sizing: border-box;
    width:70px;
    height: 28px;
}
.ac-container select {
    box-sizing: border-box;
    height:28px;
    padding-left:4px;
}
.ac-container button {
    box-sizing: border-box;
    display: inline-block;
    margin-bottom: 0;
    font-weight: bold;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
    padding: 4px 10px 4px 10px;
    font-size: 12px;
    line-height: 1.5;
    width: 84px;
    background:#8EB908;
    color:#fff;
    text-shadow:1px 1px 0 #84A51D;
}
.ac-container button:hover{
    box-sizing: border-box;
    background:#82A711;
}
.ac-container .errors  {
    box-sizing: border-box;
    margin:0 0 20px 0;
    font-size: 12px;
    line-height: 18px;
    color:#FF1F1F;
}
.ac-container .errors ul,
.ac-container .errors li{
    box-sizing: border-box;
    padding:0 0 3px 0;
    margin:0 0 0 0;
    list-style:none;
}
.ac-container .errors li span {
    box-sizing: border-box;
    font-size:9px;
    background:#ebebeb;
    border:1px solid #ccc;
    width: 14px;
    height:14px;
    border-radius:7px;
    display:inline-block;
    color:#FF1F1F;
    font-weight: bold;
    text-align: center;
    margin-right:5px;
    line-height: 13px;
    position:relative;
    top:-2px;
    text-shadow: 1px 1px 0 #fff;
    font-family:arial;
}
.ac-container .fields {
    box-sizing: border-box;
    clear:both;
    margin:10px 0 10px 0;
}
@media (max-width: 500px) {
    .ac-container {
        box-sizing: border-box;
        width:auto;
        margin-right:20px;
        margin-left:1px;
    }
    .ac-container select,
    .ac-container input.day,
    .ac-container input.year{
        box-sizing: border-box;
        display:block;
        margin-bottom:10px;
        margin-right:0;
        width:100%;
    }
    .ac-container button {
        box-sizing: border-box;
        display: block;
        width: 100%;
    }
}
</pre>
<p>This will make our box nice and friendly. Note that I&#8217;m using Google Fonts to style it. This may not be your taste &#8211; so it&#8217;s completely optional.<br />
Finally, let&#8217;s use the darn thing.</p>
<h3>How to Use:</h3>
<p>First thing you is to add the jQuery library to your page. Then download the plugin files and simply link to the .js and .css file.<br />
Next, you initialize the plugin by calling <strong>$.ageCheck()</strong> and pass in the options if necessary. See the section &#8220;Options&#8221; below for a description of the available options and default values. You can do this inside a document ready handler.</p>
<pre>
$(document).ready(function(){
   $.ageCheck();
});
</pre>
<p>Note that if you want your whole site to be restricted, you would want this prompt to appear in any of the pages your visitor hits. So the code above will be suitable in a template used throughout the site. In your header or footer is a good spot.</p>
<h3>Options:</h3>
<p>You pass options in an object literal fashion. For example, if you want to redirect the user to the login page of your site on success, you would add the option like so:</p>
<pre>
$(document).ready(function(){
   $.ageCheck({
     "redirectTo" : "http://example.com/login"
   });
});
</pre>
<p>As we&#8217;ve gone through our settings above, its good to formally list the options available. Below is a nice table that does that:</p>
<table class="table table-bordered table-striped responsive-utilities" style="margin-top:25px; margin-bottom:30px;">
<thead>
<tr>
<th>Option</th>
<th>Type</th>
<th>Description</th>
<th class="hidden-xs">Default Value</th>
</tr>
</thead>
<tbody>
<tr>
<th><code>minAge</code></th>
<td class="is-visible">Number</td>
<td>Age to validate against</td>
<td class="is-hidden hidden-xs">21</td>
</tr>
<tr>
<th><code>redirectTo</code></th>
<td class="is-hidden">String</td>
<td>URL to redirect when successful</td>
<td class="is-visible hidden-xs">None</td>
</tr>
<tr>
<th><code>title</code></th>
<td class="is-hidden">String</td>
<td>Title text above the prompt</td>
<td class="is-hidden hidden-xs">Age Verification</td>
</tr>
<tr>
<th><code>copy</code></th>
<td class="is-hidden">String</td>
<td>Paragraph text below the title</td>
<td class="is-hidden hidden-xs">This Website requires you to be [21] years or older to enter. Please enter your Date of Birth in the fields below in order to continue:</td>
</tr>
</tbody>
</table>
<h3>Conclusion</h3>
<p>Note that AgeCheck.js is a Javascript solution for verifying date of birth. Users can easily turn off Javascript in their browsers &#8211; to easily bypass the plugin. You may want a server side solution so the processing is done regardless of Javascript being on or off.<br />
For more information about how to create jQuery plugins, consult their <a href="https://learn.jquery.com/plugins/basic-plugin-creation/">documentation</a>.<br />
Let me know your thoughts below:</p>
<p>The post <a href="https://michaelsoriano.com/jquery-plugin-check-user-age/">Let&#8217;s create a jQuery Plugin that checks user&#8217;s age when visiting your site.</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/jquery-plugin-check-user-age/feed/</wfw:commentRss>
			<slash:comments>66</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s Add Next and Previous Buttons to our Bootstrap Photo Gallery</title>
		<link>https://michaelsoriano.com/next-and-previous-buttons-bootstrap-photo-gallery/</link>
					<comments>https://michaelsoriano.com/next-and-previous-buttons-bootstrap-photo-gallery/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 02 Jan 2014 07:07:55 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Bootstrap]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3875</guid>

					<description><![CDATA[<p>Update 11/14/2015: This has been converted into a jQuery plugin so the code below may be different from the demo files. For more information on how to use the plugin, read the first section in the previous tutorial. In our previous tutorial, we learned how to create a photo gallery with Bootstrap. Our gallery looks [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/next-and-previous-buttons-bootstrap-photo-gallery/">Let&#8217;s Add Next and Previous Buttons to our Bootstrap Photo Gallery</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><strong>Update 11/14/2015:</strong> This has been converted into a jQuery plugin so the code below may be different from the demo files. For more information on how to use the plugin, read the first section in the <a href="https://michaelsoriano.com/create-a-responsive-photo-gallery-with-bootstrap-framework/">previous</a> tutorial.</p>
<hr />
<p>In our previous <a title="Create a Responsive Photo Gallery with Bootstrap Framework" href="https://michaelsoriano.com/create-a-responsive-photo-gallery-with-bootstrap-framework/">tutorial</a>, we learned how to create a photo gallery with <a href="http://getbootstrap.com/">Bootstrap</a>. Our gallery looks nice and pretty, regardless of screen size. When an image is clicked, a modal box appears with a larger version of the image. If you haven&#8217;t done so, you might want to &#8220;<a title="Exploring the Bootstrap 3.0 Grid System" href="https://michaelsoriano.com/exploring-the-bootstrap-3-0-grid-system/">Explore Bootstrap&#8217;s Grid System</a>&#8221; first before getting your hands dirty.<br />
<a class="viewdemo" href="https://rawgit.com/michaelsoriano/bootstrap-photo-gallery/master/demo.html" rel="nofollow">View Demo</a><br />
<a class="" href="https://github.com/michaelsoriano/bootstrap-photo-gallery" target="_blank" rel="noopener">View in Github</a><br />
Now we&#8217;re going to add some control buttons right below the large image, so you can navigate through the gallery right in the modal window. Take a look at what we&#8217;re building in the image below.<br />
<a href="https://rawgit.com/michaelsoriano/bootstrap-photo-gallery/master/demo.html"><img decoding="async" class="alignnone size-full wp-image-3876" src="https://michaelsoriano.com/wp-content/uploads/2014/01/bootstrap-gallery-1.gif" alt="bootstrap-gallery-1" width="610" height="357" /></a><br />
I know that there are plenty of plugins that do this sort of thing. But I like doing things from scratch just to learn how things work. Ready to get started &#8211; let&#8217;s begin.</p>
<h3>Add HTML inside the &#8220;Click&#8221; Event</h3>
<p>We&#8217;re going to have to add our markup via Javascript. This is because the contents of our modal box doesn&#8217;t really exist yet when the page loads. In our last tutorial, we&#8217;re already have a click event where we&#8217;re building our large image. We simply need to append to this code. See below (in between where it says &#8220;Start of new code&#8221; and &#8220;End of new code&#8221;).</p>
<pre>
$('li img').on('click',function(){
  var src = $(this).attr('src');
  var img = '<img decoding="async" src="' + src + '" class="img-responsive"/>';
  //Start of new code
  var index = $(this).parent('li').index();
  var html = '';
  html += img;
  html += '<div style="height:25px;clear:both;display:block;">';
  html += '<a class="controls next" href="'+ (index+2) + '">next &raquo;</a>';
  html += '<a class="controls previous" href="' + (index) + '">&laquo; prev</a>';
  html += '</div>';
  //End of new code
  $('#myModal').modal();
  $('#myModal').on('shown.bs.modal', function(){
      $('#myModal .modal-body').html(html);
  })
  $('#myModal').on('hidden.bs.modal', function(){
      $('#myModal .modal-body').html('');
  });
 });
</pre>
<p><strong><u>Explanation:</u></strong> &#8211; this click event is inside the small image that was clicked. We just need to know which index it is from the list of images we have. We can achieve this by using jQuery&#8217;s <strong>.index()</strong> method. So we wrote:</p>
<pre>
var index = $(this).parent('li').index();
</pre>
<p>Meaning, we want the image that was clicked, traversing to it&#8217;s parent (list item) and grabbing it&#8217;s index. Then assigning it to a variable &#8220;index&#8221;. Note that our index is array based &#8211; so the first element is a zero.<br />
Next, we create the actual markup that we&#8217;re adding right in the modal box. You see we start with our image, then our div containing our next and previous links. You see how we consume the variable &#8220;index&#8221; that we created previously:</p>
<pre>
html += '<a class="controls next" href="'+ (index+2) + '">next &raquo;</a>';
html += '<a class="controls previous" href="' + (index) + '">&laquo; prev</a>';
</pre>
<p>Notice that our &#8220;Next&#8221; button has a &#8220;+2&#8221; for it&#8217;s &#8220;href&#8221; attribute. That&#8217;s because we want a number that is ahead of the current image that is showing, plus another because we started with zero &#8211; remember? Try out the new code by clicking on an image. As soon as our modal window pops up, you see our new previous and next buttons in place. But don&#8217;t click them yet &#8211; we haven&#8217;t written that part. <img decoding="async" class="alignnone size-full wp-image-3877" src="https://michaelsoriano.com/wp-content/uploads/2014/01/bootstrap-gallery-2.png" alt="bootstrap-gallery-2" width="593" height="389" /></p>
<h3>Create the logic when the buttons are clicked</h3>
<p>Now let&#8217;s take care of what happens when our buttons are clicked. Let&#8217;s think about what we need to achieve for a minute. First, we need to change the image &#8220;src&#8221; attribute of our large image to the next (or previous) image in the list. We already have our index so that shouldn&#8217;t be too hard. We also need to increment (or decrement) our index each time we click. Oh, we also have to hide the next button &#8211; once we get to the last image. The same behavior needs to happen to the previous button when we hit the first image. Add the code below right outside our document ready handler:</p>
<pre>
 $(document).on('click', 'a.controls', function(){
   //this is where we add our logic
   return false;
});
</pre>
<p>This just sets up our click handler for both previous and next buttons. Note that we have &#8220;.control&#8221; as a class to both links &#8211; so we only have to code once. Notice that we&#8217;re also binding the click event of our link to a parent element (in this case the document). This <a href="http://stackoverflow.com/questions/8614981/jquery-event-handler-on-not-working">binding technique</a> is used because our link is not present yet even when document is ready (reason why we wrote it outside of the .ready()).<br />
<strong><u>Replace the current image</u></strong><br />
Now let&#8217;s add this code inside our click handler:</p>
<pre>
var index = $(this).attr('href');
var src = $('ul.row li:nth-child('+ index +') img').attr('src');
$('.modal-body img').attr('src', src);
</pre>
<p><strong><u>Explanation:</u></strong> &#8211; first, we set up a variable called &#8220;index&#8221; (not the same as the index that we created previously as this is local to the anonymous function it&#8217;s in). This variable contains the number that is in the &#8220;href&#8221; of the link clicked. Variable &#8220;src&#8221; goes back to our un-ordered list, grabs the &#8220;nth-child&#8221; with the index as the number, grabs the image inside it and takes the &#8220;src&#8221; attribute.<br />
Finally, it assigns the &#8220;src&#8221; value and replaces the current image with it. <strong><u>Increment or Decrement the Link Counters</u></strong> At the same time, whenever our links are clicked, we&#8217;d want to change it&#8217;s &#8220;href&#8221; value. Add the code below:</p>
<pre>
var newPrevIndex = parseInt(index) - 1;
var newNextIndex = parseInt(newPrevIndex) + 2;
if($(this).hasClass('previous')){
    $(this).attr('href', newPrevIndex);
    $('a.next').attr('href', newNextIndex);
}else{
    $(this).attr('href', newNextIndex);
    $('a.previous').attr('href', newPrevIndex);
}
</pre>
<p><strong><u>Explanation:</u></strong> &#8211; Again, we create 2 new variables: &#8220;newPrevIndex&#8221; &#8211; which as a less than one value of the current index, and &#8220;newNextIndex&#8221; which has plus two. We then create an &#8220;if else&#8221; block. We check if the link clicked by checking it&#8217;s class, then we change both buttons &#8220;href&#8221; attributes accordingly.<br />
<strong><u>Hide links when last or first image is reached</u></strong><br />
Now we need to hide the &#8220;next&#8221; link when we reach the last image in the list and hide the &#8220;previous&#8221; when the first image is reached. We also need to re-show them when we go the opposite direction. Add the code below:</p>
<pre>
var total = $('ul.row li').length + 1;
//hide next button
if(total === newNextIndex){
    $('a.next').hide();
}else{
    $('a.next').show()
}
//hide previous button
if(newPrevIndex === 0){
    $('a.previous').hide();
}else{
    $('a.previous').show()
}
</pre>
<p><strong><u>Explanation:</u></strong> &#8211; this part is pretty simple. It simply takes the total number of list items in our gallery (var total), and makes that the basis of our comparisons. You will see the first &#8220;if&#8221; block checking if the total is the same as the new index. If it is, simply hide the &#8220;next&#8221; button, if not &#8211; show the link again. The next &#8220;if&#8221; block checks if our previous index is &#8220;0&#8221; (which is our first item), then hides and shows our &#8220;previous&#8221; link.<br />
<strong><u>What about if the last item IS clicked?</u></strong> Okay, the above code handles when the links are clicked &#8211; but what if the last OR the first item is clicked so the modal window has the first or last item. This will still have BOTH buttons in view right? In this case, we simply need to &#8220;trigger&#8221; the same click handler we just wrote above. We do this by adding the code below &#8211; right when we create the html in our modal window:</p>
<pre>
$('#myModal').on('shown.bs.modal', function(){
    $('#myModal .modal-body').html(html);
    //this will hide or show the right links:
    $('a.controls').trigger('click');
})
</pre>
<h3>Some CSS</h3>
<p>Finally, adding some styles to our links so it looks better. Note that I didn&#8217;t really spend a lot of time styling the links because this is pretty much open to your liking. Instead, I just wrote a couple of lines to make the links presentable:</p>
<pre>
.controls{
    width:50px;
    display:block;
    font-size:11px;
    padding-top:8px;
    font-weight:bold;
}
.next {
    float:right;
    text-align:right;
}
</pre>
<h3>Conclusion</h3>
<p>So now let&#8217;s see what we have: 1) a fully responsive photo gallery (Bootstrap powered), 2) a modal pop up when a thumbnail is clicked and 3) control buttons that navigate through the images once clicked. And we wrote all of this without a plugin! How cool is that! If you haven&#8217;t seen the demo, feel free to check it out <a href="https://rawgit.com/michaelsoriano/bootstrap-photo-gallery/master/demo.html" rel="nofollow">here</a>.</p>
<p>The post <a href="https://michaelsoriano.com/next-and-previous-buttons-bootstrap-photo-gallery/">Let&#8217;s Add Next and Previous Buttons to our Bootstrap Photo Gallery</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/next-and-previous-buttons-bootstrap-photo-gallery/feed/</wfw:commentRss>
			<slash:comments>66</slash:comments>
		
		
			</item>
		<item>
		<title>Build a Simple Responsive Navigation Menu from scratch with jQuery and CSS</title>
		<link>https://michaelsoriano.com/build-a-simple-responsive-navigation-menu-from-scratch/</link>
					<comments>https://michaelsoriano.com/build-a-simple-responsive-navigation-menu-from-scratch/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 21 Oct 2013 05:12:48 +0000</pubDate>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3686</guid>

					<description><![CDATA[<p>Follow this tutorial to create your own responsive navigation menu without a plugin. So far one of the hardest parts of designing a responsive website is the dreaded navigation menu. I know because I&#8217;ve always struggled with it. I&#8217;ve seen plenty of plugins that convert your menu into a drop down list, or a fancy [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/build-a-simple-responsive-navigation-menu-from-scratch/">Build a Simple Responsive Navigation Menu from scratch with jQuery and CSS</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Follow this tutorial to create your own responsive navigation menu without a plugin.<br />
So far one of the hardest parts of designing a responsive website is the dreaded navigation menu. I know because I&#8217;ve always struggled with it. I&#8217;ve seen plenty of plugins that convert your menu into a drop down list, or a fancy side menu that pushes your content to the left. But I wasn&#8217;t happy with them. So I decided to write one of my own.<br />
<a class="viewdemo" href="http://demo.michaelsoriano.com/responsive-menu/" rel="nofollow">View Demo</a><br />
<img decoding="async" class="alignnone size-full wp-image-4376" src="https://michaelsoriano.com/wp-content/uploads/2013/10/responsive-menu.gif" alt="responsive-menu" width="598" height="358" /><br />
Nothing fancy here. I just want to simply hide the horizontal menu, show an icon and when clicked &#8211; have the &#8220;mini-navigation&#8221; show as a standard list &#8211; pushing the rest of the content down. Ready to get started? Let&#8217;s begin.</p>
<h3>The Problem</h3>
<p>Most navigation menus is marked up with list items that are floated left. While this is good with desktop resolutions, it doesn&#8217;t work well when the view port is for small screens.<br />
<img decoding="async" class="alignnone noborder size-full wp-image-3688" src="https://michaelsoriano.com/wp-content/uploads/2013/10/resp-nav-11.jpg" alt="resp-nav-1" width="600" height="251" /><br />
As I&#8217;ve mentioned above, we&#8217;ll get our way around this problem by hiding the original menu and showing a new one. This can all be achieved by CSS and a little jQuery. Take a look at the existing markup for the menu.<br />
<em>code taken out &#8211; due to problems with my plugin</em></p>
<h3>Create the Media Query</h3>
<p>Let&#8217;s add a media query in our CSS for max width of 796 pixels. We then hide the list items by setting a &#8220;display none&#8221; inside the query.</p>
<pre>@media (max-width: 796px) {
 .navigation.responsive ul li {
   display:none;
}
</pre>
<p>Now try re-sizing your browser to less than 796 pixels and see that the contents of our menu disappears.</p>
<h3>Add the Trigger and Empty Div into the Markup</h3>
<p>We&#8217;re going to need a new anchor tag into our existing menu, also known as the &#8220;trigger&#8221;. We can simply add a last list item to our navigation menu &#8211; but set it to &#8220;display:none&#8221;. I&#8217;ve created a class in our CSS called &#8220;hidden&#8221;, to simply use that with our trigger.<br />
Then add an empty DIV outside of our current navigation. I&#8217;ve named our new DIV &#8220;mini-navigation&#8221;. I also added the &#8220;hidden&#8221; class to this DIV, so both our trigger and mini-nav won&#8217;t be visible by default. Our markup should now look like below:<br />
<em>code taken out &#8211; due to problems with my plugin</em></p>
<div class="navigation responsive"></div>
<p>Note the last list item and our empty DIV above.</p>
<h3>Show the Trigger in our Media Query</h3>
<p>Inside our media query, add these lines to our CSS:</p>
<pre>.navigation.responsive ul li.hidden {
  display:block;
}
.navigation.responsive ul li.hidden:hover {
  border-radius:4px 0 0 4px;
}
.navigation.responsive ul li.hidden a{
  background:url('menu.png')no-repeat 0 -5px;
  padding-left:24px;
}
</pre>
<p>Note that the key code in the above is the &#8220;display:block&#8221;. This will make our trigger be visible. The rest of the code simply styles our trigger so it will look like below:<br />
<img decoding="async" class="alignnone noborder size-full wp-image-3689" src="https://michaelsoriano.com/wp-content/uploads/2013/10/resp-nav-2.jpg" alt="resp-nav-2" width="512" height="123" /></p>
<h3>Add the Javascript</h3>
<p>Now that we have our trigger, we need Javascript to handle what happens when it is clicked. First, make sure you&#8217;re hooked up with jQuery in your page.<br />
Then let&#8217;s add the following code in a set of script tags. I&#8217;ll explain what it does after the source.</p>
<pre>$(document).ready(function(){
	var trigger = $(".trigger a");
	var menu = $(".mini-navigation");
	trigger.on('click', function(){
		var html = $(".navigation.responsive").html();
		menu.html(html).toggle(0, function(){
		  if($(this).is(":visible")){
			trigger.html('Hide Menu');
				}else{
					trigger.html('Show Menu');
				}
			$('.mini-navigation li.trigger').remove();
			});
		});
		$(window).resize(function(){
			menu.hide();
			trigger.html('Show Menu');
		});
	})
</pre>
<p>Let me explain the code above. First we open the document.ready() function. We then set two variables: trigger(our trigger link) and menu(our hidden div). We bind the click event by using doing trigger.on(). Everything inside the .on() anonymous function is the heart of the code.<br />
We create another variable called &#8220;hmtl&#8221; &#8211; which is the contents of our existing navigation. We then add it to our hidden div by doing: menu.html(html). So our hidden div (mini-navigation) now has our list items from the original menu.<br />
We then chain the .toggle() function right after the .html(). This will show or hide our hidden div. We add an if else statement as a callback inside the .toggle(), just to change the label of our trigger from &#8220;Show Menu&#8221; to &#8220;Hide Menu&#8221;.<br />
We also remove the last list item (which is the duplicate trigger).<br />
Finally, we have window.resize() function &#8211; which simply resets our menu back to hidden and the label to &#8220;Show Menu&#8221; &#8211; which are the default states.</p>
<h3>Style the Mini Navigation</h3>
<p>This is of course, open to your customization. But what I&#8217;ve done is simply make our new menu a list item, with some bottom borders, appropriate padding and hover states.</p>
<pre>.mini-navigation {
	border-left:1px solid #ccc;
	border-bottom:1px solid #ccc;
	border-right:1px solid #ccc;
	padding:0 0 0 0;
	margin-left:5px;
	margin-right:5px;
	border-radius:0 0 8px 8px;
}
.mini-navigation ul {
	padding:0 0 0 0;
	margin:0 0 0 0;
}
.mini-navigation ul li {
	margin:0 0 0 0;
	padding:10px 18px 12px 23px;
	list-style:none;
	border-bottom:1px solid #ebebeb;
}
.mini-navigation ul li:hover {
	background:#f6f6f6;
}
.mini-navigation ul li a {
	text-decoration:none;
	font-size:12px;
	color:#1e7759;
}
.mini-navigation ul li a:hover {
	text-decoration:underline;
}
.mini-navigation ul li:last-child{
	border-bottom:none;
	padding-bottom:15px;
}
.mini-navigation ul li:last-child:hover {
	border-radius:0 0 8px 8px;
}
</pre>
<p>Our mini navigation should look like below:<br />
<img decoding="async" class="alignnone noborder size-full wp-image-3690" src="https://michaelsoriano.com/wp-content/uploads/2013/10/resp-nav-3.jpg" alt="resp-nav-3" width="577" height="423" /><br />
Note that typically, the navigation is right above the rest of your content. When our menu appears &#8211; it simply pushes the rest of the content downwards. And when the new page loads &#8211; our menu returns to hidden by default.</p>
<h3>Conclusion</h3>
<p>And I believe that should do it. That&#8217;s as simple as it gets. Our very own responsive navigation menu system. Please leave your comments below.</p>
<p>The post <a href="https://michaelsoriano.com/build-a-simple-responsive-navigation-menu-from-scratch/">Build a Simple Responsive Navigation Menu from scratch with jQuery and CSS</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/build-a-simple-responsive-navigation-menu-from-scratch/feed/</wfw:commentRss>
			<slash:comments>9</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create a jQuery Image Rotator from Scratch</title>
		<link>https://michaelsoriano.com/how-to-create-a-jquery-image-rotator/</link>
					<comments>https://michaelsoriano.com/how-to-create-a-jquery-image-rotator/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 01 Dec 2012 23:12:06 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=3009</guid>

					<description><![CDATA[<p>Learn how to code a simple Image Rotator without using a plugin So it&#8217;s that time again to roll up our sleeves and do some old fashioned front end a&#8217; coding. This tutorial is for an Image Rotator. What is it you ask? An Image Rotator is particularly useful for galleries, articles, or portfolios. You [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-a-jquery-image-rotator/">How to Create a jQuery Image Rotator from Scratch</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h4>Learn how to code a simple Image Rotator without using a plugin</h4>
<p>So it&#8217;s that time again to roll up our sleeves and do some old fashioned front end a&#8217; coding. This tutorial is for an Image Rotator. What is it you ask? An Image Rotator is particularly useful for galleries, articles, or portfolios. You can use it just about anywhere you want to cycle through content. First, take a look at the demo to see what we&#8217;re building:<br />
<a class="viewdemo" href="http://demo.michaelsoriano.com/image-rotator/" rel="nofollow">View Demo</a><br />
But there&#8217;s hundreds of plugins out there that do this same thing? True &#8211; but there&#8217;s nothing like writing one for yourself. See, the problem with using a plugin &#8211; is that you&#8217;re quite limited to the options that they allow you to pass. By writing one for yourself &#8211; you know exactly what&#8217;s going on and you have total control of what goes on. Ready to get started?<br />
<img decoding="async" class="alignnone size-full wp-image-4371 noborder" src="https://michaelsoriano.com/wp-content/uploads/2012/12/im-rotator.gif" alt="im-rotator" width="574" height="391" /></p>
<h3>The Markup</h3>
<p>The challenge is: we want a clean markup as possible. This makes it easy for search engines to crawl through our content. Start with the code below:</p>
<div id="featured">
&nbsp;</p>
<ul class="tabs">
<li style="list-style-type: none">
<ul class="tabs">
<li>Smelling the air</li>
</ul>
</li>
</ul>
<p>&nbsp;</p>
<ul class="tabs">
<li style="list-style-type: none">
<ul class="tabs">
<li>Some Crazy Colors</li>
</ul>
</li>
</ul>
<p>&nbsp;</p>
<ul class="tabs">
<li style="list-style-type: none">
<ul class="tabs">
<li>Awesome Hairdo</li>
</ul>
</li>
</ul>
<p>&nbsp;</p>
<ul class="tabs">
<li style="list-style-type: none">
<ul class="tabs">
<li>Color Cans Bruh</li>
</ul>
</li>
</ul>
<p>&nbsp;</p>
<ul class="tabs">
<li style="list-style-type: none">
<ul class="tabs">
<li>Grafitti All Over</li>
</ul>
</li>
</ul>
<p>&nbsp;<br />
&nbsp;</p>
<div class="container"><img decoding="async" src="images/image1.jpg" /></div>
<p>&nbsp;</p>
<div class="container"><img decoding="async" src="images/image2.jpg" /></div>
<p>&nbsp;</p>
<div class="container"><img decoding="async" src="images/image3.jpg" /></div>
<p>&nbsp;</p>
<div class="container"><img decoding="async" src="images/image4.jpg" /></div>
<p>&nbsp;</p>
<div class="container"><img decoding="async" src="images/image5.jpg" /></div>
<p>&nbsp;
</p></div>
<p>&nbsp;<br />
You see, all we have is a mother div. Inside is an unordered list followed by images with enclosed divs around them. This is enough to get our Rotator cooking.<br />
<img decoding="async" class="alignnone size-full wp-image-3013" title="rotator-0" src="https://michaelsoriano.com/wp-content/uploads/2012/12/rotator-0.jpg" alt="" width="531" height="569" /></p>
<h3>Add Some Javascript</h3>
<p>We&#8217;re going to use the jQuery Library for our Rotator because of it&#8217;s ease of use, and browser compatibility. Make sure in your HTML, you link to the library.<br />
Then open up another script tag, and place the code below:</p>
<pre>$(document).ready(function(){
 $('.container').each(function(e){
  if(e == 0){
   $(this).addClass('current');
  }
  $(this).attr('id', 'handle' + e);
})
</pre>
<p>This loops through all of our &#8220;container&#8221; divs and adds an &#8220;id&#8221; attribute to them. The Ids are called &#8220;handle&#8221; along with &#8220;e&#8221; &#8211; which is the index (a number for each of them). It also adds a class &#8220;current&#8221; to the first one it finds.<br />
<img decoding="async" class="alignnone size-full wp-image-3011" title="rotator-2" src="https://michaelsoriano.com/wp-content/uploads/2012/12/rotator-2.jpg" alt="" width="533" height="539" /><br />
Next, add the code below inside the document ready clause.</p>
<pre>$('.tabs li').each(function(e){
	if(e == 0){
		$(this).addClass('current');
	}
	$(this).wrapInner('');
	$(this).append('<a><img /></a>');
	$(this).children('a').attr('href', '#handle' + e);
	y = $('#handle' + e + ' img').attr('src');
	$(this).find('img').attr('src', y);
	t = $(this).children('a').text();
	$('#handle' + e).append('</pre>
<h2>&#8216; + t + &#8216;</h2>
<p>&#8216;); })<br />
Line by line &#8211; the code above loops through each of our list items (li tags). It adds the class &#8220;current&#8221; to the first one it finds. Then wraps the text inside around an anchor tag with class &#8220;title&#8221;. It then appends another anchor tag with an image inside of them. It finds all of the anchor tags and adds attribute &#8220;href&#8221; &#8211; with a link to &#8220;#handle&#8221; plus &#8220;e&#8221; (Remember the ids we assigned to the containers a while ago?).<br />
You see the variable &#8220;y&#8221; &#8211; it&#8217;s actually grabbing the large image&#8217;s src attribute and storing it in a temporary variable, then assigns it to the small image that we&#8217;ve dynamically created above. Finally, variable &#8220;t&#8221; is grabbing the list item&#8217;s text &#8211; and assigns it to an H2 tag for the large images. Take a look at your mark up now:<br />
<img decoding="async" class="alignnone size-full wp-image-3012" title="rotator-3" src="https://michaelsoriano.com/wp-content/uploads/2012/12/rotator-3.jpg" alt="" width="520" height="608" /></p>
<h6>Some Events</h6>
<p>We have our clean markup, we&#8217;ve dynamically altered it with Javascript and now we&#8217;re creating some events. We want the images to automatically rotate, as well as switch once the small images are clicked. Let&#8217;s do that first.<br />
Add the lines of code below:</p>
<pre>$('.tabs li a').click(function(){
	c = $(this).attr('href');
	if($(c).hasClass('current')){
		return false;
	}else{
		showImage($(c), 20);
		$('.tabs li').removeClass('current');
		$(this).parent().addClass('current');
		return false;
	}
})
</pre>
<p>The above code adds some events once we click any of the anchor tags inside our li tags. It first checks that if the container we&#8217;re clicking for has a &#8220;current&#8221; class &#8211; we immediately exit (by calling return false). If it doesn&#8217;t, we run a function called &#8220;showImage&#8221; (which we haven&#8217;t built yet). It also removes ANY &#8220;current&#8221; class on ALL li tags, then adds &#8220;current&#8221; ONLY to it&#8217;s parent.</p>
<h6>The showImage() Function</h6>
<p>We create functions so we can reuse it anywhere in our code. The showImage() function simply changes the z-index property and opacity of the image container.</p>
<pre>function showImage(img, duration){
	$('.container').removeClass('current').css({
			"opacity" : 0.0,
			"zIndex" : 2
			});
	img.animate({opacity:1.0}, duration, function(){
		$(this).addClass('current').css({zIndex:1});
	});
}
</pre>
<p>Place the above code outside of the document.ready clause (but inside our script tags). You notice that showImage() accepts two parameters &#8211; the image and duration. In our previous click event &#8211; we pass &#8220;c&#8221; &#8211; which was the &#8220;href&#8221; value of whichever anchor tag we clicked. We also pass &#8220;20&#8221; &#8211; which means 20 milliseconds.</p>
<h6>The rotateImages() Function</h6>
<p>Now we want to automatically cycle through the large and small images. We create two functions for this &#8211; rotateImages() and runRotateImages(). The main one &#8211; rotateImages() does all of the work:</p>
<pre>function runRotateImages(){
  function rotateImages(){
    var curPhoto = $("div.current");
    var nxtPhoto = curPhoto.next();
    var curTab = $(".tabs li.current");
    var nxtTab = curTab.next();
    if (nxtPhoto.length == 0) {
      nxtPhoto = $('#featured div:first');
      nxtTab = $('.tabs li:first-child');
    }
    curTab.removeClass('current');
    nxtTab.addClass('current');
    showImage(nxtPhoto, 300);
  }
	theRotator = setInterval(rotateImages(), 4000);
}
</pre>
<p>It first looks for the list items, and container with the &#8220;current&#8221; class in them. Note that this could be the first &#8211; or anyone of them once we click. Then it checks if there&#8217;s no div after it by checking length &#8220;(nxtPhoto.length == 0)&#8221;, and goes back to the first list item and div if there&#8217;s none.<br />
Again, it removes &#8220;current&#8221; class and adds it to the next. Finally, we run the &#8220;showImage()&#8221; function and pass &#8220;nxtPhoto&#8221; and 300 milliseconds. As you might have guessed, runRotateImages() simply runs rotateImages(). But it is wrapped in setInterval() and assigned to a variable &#8220;theRotator&#8221;. This will allow us to pause and proceed with our animation at any given time.<br />
Let&#8217;s add the call to our two functions inside the document.ready clause:</p>
<pre>runRotateImages();
var theRotator;
  $("#featured").hover(
	function(){
          clearTimeout(theRotator);
	},
	function(){
	  runRotateImages();
	}
  )
</pre>
<p>The above runs our main animation, then we create a pause on hover() on top of our main div by using &#8220;clearTimeout()&#8221;. It proceeds to our main function on hover out.<br />
We can&#8217;t preview any of our code as of yet &#8211; we can&#8217;t really see improvements at this stage. Let&#8217;s beautify our work with some styles. That&#8217;s coming up next.</p>
<h3>Some CSS Magic</h3>
<p>Here we are, the final part of our exercise. If you&#8217;ve stuck with me all this time &#8211; you guys are true web devs. So I&#8217;m not going to explain what the style does &#8211; you can figure that out for yourself. Wrap the code below in a set of style tags:</p>
<pre>#featured{
	width:518px;
	padding: 18px 120px 10px 21px;
	background:  #ebebeb !important;
	position:relative;
	border:1px solid #ccc;
	height:434px;
	background:#fff;
	margin-bottom:35px;
	border-radius:6px;
	-moz-border-radius:6px;
	-webkit-border-radius:6px;
}
#featured ul.tabs{
	position:absolute;
	top:18px;
	left:538px;
	padding:0;
	margin:0;
}
#featured ul.tabs li{
	font-size:10px;
	color:#666;
	line-height:10px;
	height:75px;
	color:#333;
	overflow:hidden;
	width:96px;
	background:#fff;
	margin-bottom:11px;
	position:relative;
}
#featured ul.tabs li a.title{
	position:absolute;
	z-index:5;
	color:#fff;
	font-family:arial;
	bottom:7px;
	width:96px;
	text-align:center;
	text-shadow:1px -1px 0 #000;
	text-decoration:none;
}
#featured ul.tabs li img {
	width:96px;
	height:75px;
	opacity:0.5;
	z-index:3;
}
#featured ul.tabs li.current img, #featured ul.tabs li img:hover {
	opacity:1.0;
}
#featured div.container img {
	height: 420px;
    width: 500px;
	position:absolute;
}
#featured div.container {position:relative; z-index:0;}
#featured div.container.previous {z-index:1;}
#featured div.container.current {z-index:2;}
#featured h2{
	font-size:40px;
	font-family:Arial;
	color:#fff;
	padding:5px 5px 5px 12px; margin:0;
	overflow:hidden;
	line-height:65px;
	text-transform:uppercase;
	height:50px; overflow:hidden;
	position:absolute;
	top:350px;
	text-shadow:1px -1px 0 #000;
	text-align:center;
	letter-spacing:-1px;
	width:475px;
}
</pre>
<p>Simply put, the CSS arranges all of the big images into an absolute position &#8211; so they&#8217;re all stacked up on top of each other. The list items are also positon &#8211; but to the right of the large images. Additional styles are added to the current list items: less opacity on the inactive ones. This gives a nice touch to our animation. The rest are styles related to the demo file.</p>
<h3>Conclusion</h3>
<p>There are no download files for this tutorial &#8211; you can simply go to the demo and view it&#8217;s source and copy it. My intentions are for you to actually follow the above tutorial and do it yourself. Also check out these Image Rotators that are have different approaches code-wise, but the final output is somewhat similar.</p>
<ul>
<li><a href="http://tympanus.net/codrops/2011/01/03/parallax-slider/">Parallax Slider with jQuery</a></li>
<li><a href="http://css-plus.com/2010/09/create-your-own-jquery-image-slider/">Create your own jQuery Image Slider</a></li>
<li><a href="http://webdeveloperplus.com/jquery/featured-content-slider-using-jquery-ui/">Create Featured Content Slider Using jQuery UI</a></li>
</ul>
<p>The post <a href="https://michaelsoriano.com/how-to-create-a-jquery-image-rotator/">How to Create a jQuery Image Rotator from Scratch</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-create-a-jquery-image-rotator/feed/</wfw:commentRss>
			<slash:comments>34</slash:comments>
		
		
			</item>
		<item>
		<title>How to Create Super Easy jQuery Tab Containers</title>
		<link>https://michaelsoriano.com/how-to-create-super-easy-jquery-tabbed-containers/</link>
					<comments>https://michaelsoriano.com/how-to-create-super-easy-jquery-tabbed-containers/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sun, 01 Jan 2012 18:29:12 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<guid isPermaLink="false">http://fearlessflyer.com/?p=2324</guid>

					<description><![CDATA[<p>In this tutorial I&#8217;m going to show you how to create tabbed containers using jQuery. Tabbed containers is an excellent way of presenting your content. Data is organized where only the current tab&#8217;s section is shown. Once the user clicks on the other tabs, its associated content gracefully appears. View Demo Here&#8217;s a preview of [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-super-easy-jquery-tabbed-containers/">How to Create Super Easy jQuery Tab Containers</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>In this tutorial I&#8217;m going to show you how to create tabbed containers using jQuery. Tabbed containers is an excellent way of presenting your content. Data is organized where only the current tab&#8217;s section is shown. Once the user clicks on the other tabs, its associated content gracefully appears.<br />
<a class="viewdemo" href="http://demo.michaelsoriano.com/tabbed-containers/">View Demo</a><br />
Here&#8217;s a preview of what we&#8217;re building:<br />
<img decoding="async" class="noborder alignnone size-full wp-image-4373" src="https://michaelsoriano.com/wp-content/uploads/2012/01/tabbed-containers-animated.gif" alt="tabbed-containers-animated" width="636" height="434" /><br />
Please note that you will need to know some HTML / CSS and a little Javascript scripting to follow. Ready to get started? Let&#8217;s begin:</p>
<h3>Set up the HTML:</h3>
<p>First and foremost &#8211; we need the markup. We need this so we know what we are styling and manipulating. We are going to use semantic and valid HTML. In addition, we will keep it as clean as possible &#8211; with no unnecessary DIVs and classes in our code:<br />
<script src="https://gist.github.com/michaelsoriano/a36236bb4a319731b224.js"></script><br />
As you can see, our markup is pretty self-explanatory. The UL items will be our tabs, while the DIVs below it are the containers. Save your file and view it in the browser:<br />
<img decoding="async" class="alignnone size-full wp-image-2325" title="tutorial1" src="https://michaelsoriano.com/wp-content/uploads/2011/12/tutorial1.jpg" alt="" width="446" height="399" /></p>
<h3>Add Some Sweet Styles:</h3>
<p>I usually like to style the HTML right after. This way &#8211; I can write the script exactly how to behave. Moreover, we can decide if what classes to add via Javascript.</p>
<h6>The Tabs</h6>
<p>Let&#8217;s convert our unordered list into tabs:<br />
<script src="https://gist.github.com/michaelsoriano/f4c3240867179216669e.js"></script><br />
Save your file and view it in the browser:<br />
<img decoding="async" class="alignnone size-full wp-image-2327" title="tutorial2" src="https://michaelsoriano.com/wp-content/uploads/2011/12/tutorial2.jpg" alt="" width="500" height="284" /><br />
Beautiful right? Things are coming along. We also want to add a style for the &#8220;inactive&#8221; state of the tabs. This will be how the tabs will look when they&#8217;re not in focus. Add the code below to your stylesheet:<br />
<script src="https://gist.github.com/michaelsoriano/284b7da4bcaf2dc5e5cd.js"></script><br />
Notice that I also added a separate style for <em>:hover</em>. To see how these styles look, you have to manually add class &#8220;inactive&#8221; to the anchor tags in our tabs, and refresh your browser:<br />
<img decoding="async" class="alignnone work size-full wp-image-2328" title="tutorial3" src="https://michaelsoriano.com/wp-content/uploads/2011/12/tutorial3.jpg" alt="" width="439" height="236" /></p>
<h6>The Containers</h6>
<p>The containers styles really depend on you. I just added some general rules such as width and appropriate paddings:<br />
<script src="https://gist.github.com/michaelsoriano/1e3da98a2a74bb8a0bbf.js"></script><br />
Now we have a solid look and we can continue with the scripting. Be sure to add some dummy content to your containers before we go on.</p>
<h3>The jQuery</h3>
<p>This part may have the shortest code, but will do a lot of work. Lets include the jQuery library into our page and start our document ready event. Append this code into your HTML:<br />
<script src="https://gist.github.com/michaelsoriano/d5d86a53c81b6a7d6eb5.js"></script><br />
Now we need a way make our tabs inactive and hide the containers. Add the lines of code inside our document ready block:<br />
<script src="https://gist.github.com/michaelsoriano/edadc2f4026264ccb300.js"></script><br />
The code above adds the class &#8220;inactive&#8221; to all our our tabs &#8211; except the first one using the &#8220;:not(:first)&#8221; filter. The second line hides all of our container divs &#8211; except the first one, again using the said filter.<br />
Refresh your browser and you shall see the effects:<br />
<img decoding="async" class="alignnone size-full wp-image-2330" title="tutorial4" src="https://michaelsoriano.com/wp-content/uploads/2011/12/tutorial4.jpg" alt="" width="500" height="428" /><br />
Now let&#8217;s add a click handler to our tabs along with the events. Add the lines of code also inside document ready:<br />
<script src="https://gist.github.com/michaelsoriano/ac9c30dd8ba760b7f883.js"></script><br />
A lot of things are happening here &#8211; first &#8211; we&#8217;ve established a click handler to our tabs. We also created a variable &#8220;t&#8221; that represents the value of the &#8220;href&#8221; attribute for whichever anchor tag that was clicked. For instance, if the first tab was clicked, then &#8220;t&#8221; will be &#8220;#tab1&#8221;. Then we add class &#8220;inactive&#8221; to all of the tabs, while removing &#8220;inactive&#8221; to whichever one was clicked. Then, we hide all of the containers while fading in the one that is &#8220;t&#8221;, i.e. #tab1 or #tab2 and so on. Return false just prevents the anchor links from their default behavior.<br />
Refresh your browser and try it out. So our tabs are in full action. There is one problem though: when you click the current tab &#8211; it still attempts to hide all the containers and show the current one &#8211; we don&#8217;t want this to happen. Let&#8217;s add a conditional block to our code:<br />
<script src="https://gist.github.com/michaelsoriano/5b81f8451282d89eb192.js"></script><br />
Wrapping our events inside this if block prevents this unwanted behavior.</p>
<h3>Conclusion</h3>
<p>And there you have it. Wasn&#8217;t that easy? Super Easy? The best thing about this code is it doesn&#8217;t use any images. All of the gradients and shadows are CSS3. Also, it is backwards compatible for users without Javascript. It won&#8217;t work as tabs &#8211; but it will show the full content, and the tabs will still lead them to the right area when clicked.</p>
<p>The post <a href="https://michaelsoriano.com/how-to-create-super-easy-jquery-tabbed-containers/">How to Create Super Easy jQuery Tab Containers</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/how-to-create-super-easy-jquery-tabbed-containers/feed/</wfw:commentRss>
			<slash:comments>45</slash:comments>
		
		
			</item>
	</channel>
</rss>
