Archive for jQuery / Javascript

Limit Character Count in ACF Repeater Text Field

Limiting the characters in a given field is a good way to dummyproof your admin dashboard so content writers don’t write novel length entries for a field that should only be a few words. This could have consequences such as ruining the integrity of the design and brand the company wishes to achieve. So limiting the length of the content they can write is a good way to make sure things like that don’t happen.

However, this is not a feature supported by the ACF plugin at the moment. So there is a work around that can get the desired effect until they do. Just put this code in your functions.php file:

<?php function my_head_input() { ?>
<script type="text/javascript">
jQuery(function(){
    jQuery('.repeater textarea').css("min-height","5px");
    jQuery('.repeater textarea').on('keyup', function(){
    var characters = 30;
    if( jQuery(this).val().length > characters ){
      jQuery(this).val(jQuery(this).val().substr(0, characters));
      return false;
    }
  });
});
</script>
<?php }
add_action('acf/input/admin_head' , 'my_head_input' );
?>

this solution was tailored to the textarea fields of all repeater fields. You can play with the jQuery selector to affect the fields you desire
Source

jQuery animate from “PX” to “AUTO”

so if I have the CSS property “top” equal to ‘auto and i animate it to be “30px” and I want to change it back to auto… i should be able to just do:

$('.section').animate({'top':'auto'},500);

right? WRONG! You can’t animate to auto, so how do you change it back? Sure, you can set the CSS to be that, but not useful if you want an animation with it. The solution involves some math and customization on your part, but i can go through what made it work on my end.

First you need to find out what “auto” really is. You’ll need to calculate this based on the parent elements.

var windowHeight = $('.page').height(); //height of parent div
var desiredOffset = 140; //offset from the bottom
var newPosition = windowHeight - desiredOffset+'px';

Taking this value, you can animate the CSS property of top to that value. Now if your parent is based on the window height, that top value isn’t going to work… so after your done animating it to the top for that browser height, you can then use jQuery’s CSS function to simply change back to top:auto / remove the added style you just applied. (since it should be theoretically the same location as the top CSS you just calculated to animate to. So all together it would be:

var windowHeight = $('.page').height();
var desiredOffset = 140;
var newPosition = windowHeight - desiredOffset +'px';
$('.section').animate({'top':newPosition},500);
$('.section').delay(600).stop().removeAttr('style');

Source

Mobile app protocols. Open from your mobile Safari!

So you are developing your mobile site and were asked to open links inside of apps. Maybe you are just feeling ambitious!

Well this is my instructions for linking app protocols while not completely isolating people who don’t have the apps.

Lets start by discussing the main barriers we have. Inside of native apps we have the ability to test “canOpenURL” but this is lost in browsers. Browsers will not accept any protocols such as twitter:// or fb:// . So what really happens when you send those protocols is the phone does a GET, upon the response it sees the protocol is fb:// or twitter:// or any:// and if it is supported on the phone, it will trigger the respective app to open.

The browser will NEVER get a return from the GET it posted. So there is literally no current way to test if protocols are supported on a phone using any type of javascript or PHP that I know of. (NOTE: if YOU do, comment that would be awesome).

First lets set up our element links. Instead of using hrefs we are going to load both a browser link, and an app protocol link as data attributes. It’s mobile browsers so they should all support data attributes.

<a data-link="fb://profile/YOURID" data-browserLink="http://facebook.com/YOURPAGE" class="fbLink" target="_blank"><img src="<?php bloginfo( 'template_url' ); ?>/images/facebook.png"/></a>

So this is the basic link element. data-link is your link for people with the facebook app. data-browserLink is your link for people who don’t have Facebook. Now that you have that lets move onto the execution part of this. Use the class to trigger a click event in javascript/jQuery. We should also make a global variable and you will find out why in a little bit.

 

$(document).ready(function(){
			 $(".fbLink").click(testLink);
 
		   });
//This should trigger a function that you have named "testLink"
 
var webURL = '';

Now write your function.

What it should essentially do is:

Change your document location to your protocol link, triggering a GET.

Wait for a response and then offer the user the ability to open the link in their mobile browser.

 

function testLink(){
				//set webURL so that it still has it's definition in the timeout function.
				webURL = $(this).data('browserlink');
 			 document.location = $(this).data('link');
 				 setTimeout(function(){
			    if(confirm('You do not seem to have this app installed. Would you like to view it in your browser')){
 				     window.open(webURL);
 		   }
 			 }, 100);
			}

This is the fix I came up with.

One note: You will probably always get the option to open in browser from the confirm. That’s because the browser never seems to actually receive a response.

Whats the best WYSIWYG editor?

So1WebDesigner made their list of top 10 in browser WYSIWYG plugins, and I am compelled to agree.

My favorite WYSIWYG editor plugin is by far NicEdit.

I’m going to show you some basic highlights of their documentation for a standard WYSIWYG.

First thing is to take your text area and define it with an ID

<textarea id="YourID">

So that’s nice, good job!

Now we want to do the actual function.

One thing I suggest is to not have the gif file that comes with the install right next to your js file. But they have this nice little function not a lot of people know about called, iconsPath.

I’ll show you my typical code for this editor.

{
 
new nicEditor({fullPanel : true, iconsPath : '/YOURPATH/nicEditorIcons.gif'}).panelInstance('YOURID');
 
}

And that is a simple WYSIWYG editor from NicEdit.

Youtube Wall Viewer.

I know it sounds a little weird to have a wall for pulling youtube videos.

One thing i was exploring is the concept of dynamically created video pages, which pull from youtube, vimeo and other such media outlets.

The fine folks made a “Socialist” Plugin, sourced at the bottom of the file.

I also use pop up windows also sourced.

Take a look, and like most things. This page can be used to display youtube walls while letting the users choose their own channels probably by using a CMS.

Youtube Wall Viewer.

Of SEO and Hashbang

There is a lot of discussion going on right now about the hashbang (#!) URL’s. If you’re contemplating using them, this article should help you to decide one way or another.

How it Works – The Good

The hashbang works mainly with AJAX, which is super cool. The distinguishing feature of hashbang is that it creates a change in the URL to load another “page” within your current page. The theory behind this is that users will not feel like they are navigating away from your home page. It will work very much like a traditional application in terms of appearance and concept. It also allows for neat page transitions, which are possible with the more traditional AJAX.

The biggest thing going for hashbang is that it allows search engine to index the site. Unfortunately, that’s only in theory. When it comes to practice, the hashbang syntax doesn’t work as well with SEO as it was originally supposed. Google does recognize the syntax and indexes accordinglly, but none of the other search engines recognize the hashbang, which makes for a less than desirable result.

What it Breaks – The Bad

The unfortunate part of working with hashbangs is its heavy reliance upon JavaScript for…well…everything. If a user has JavaScript disabled, your site will either display no content whatsoever, or you will need to display it in a different manner for users without JavaScript. This might not be a big deal, depending on who might access your site. Most people do have JavaScript these days, so the number of users affected is minimal.

The other unfortunate part of the URL is that not all users can remember abstract characters like they might be able to remember a SEO-friendly URL. The popular social media sites, such as Twitter, YouTube, and FaceBook have URL’s down to where the only thing after the site address is the user’s username. (example: http://www.facebook.com/BarsnessSolutions) This makes it easy for users to remember URL’s if they’re going to. Since most SEO-friendly sites do use this syntax, departing from it makes the whole thing less user-friendly, if only for the small percentage that type URL’s instead of googling and clicking every time.

What it Replaces – The Ugly

The great part about hashbangs is that it is compatible across platforms. Regular AJAX can do this, but without the URL change essential to search engines. The other (and perhaps better) alternative is HTML5′s Push-State, which allows the same activity, but with cleaner URL’s and universal recognition by search engines. The biggest disadvantage of the Push-State implementation is that it is only partially recognized by Safari and not at all in Internet Explorer before version 10.

In summary, I think that the concept of hashbang syntax is absolutely right, but the world of web is not ready to accept it. I think that in the long term, the HTML5 implementation will take precedence and hashbang will go away. Until then, however, the choice is yours.

Gallery Shadow Toggler

So I recently built this gallery shadow toggler. Using the evals in my last post. Also using some awesome plugins such as jQery Shadow.

Image is from SXU.

Take a look, mind the notes at the bottom, let me know if you have any questions.

Gallery Shadow Toggler.

Lets execute some evals from data attributes!!

Ok so in making a super cool piece of code I came across a problem. I wanted to pull some functions from the data attributes on some elements.

This could be for any reason. Lets pretend you have some functions you need to be able to execute after page load, depending on what the user clicks.

The  first step is to make your functions and we will embed them in our elements using the data attribute that Andy Stramer talked to you about in the post HTML data attributes with jQuery.

do it in this way

 
<div class="whateverclassyouwant" data-function="function(){insertanyfunctionhere}" > </div>

So what this does is stores an entire function as a string inside the elements you might be passing from the server.

Now what we do is some awesome javascript and jQuery:

 
function executeThisOnElementClick(){
        var method = $(this).data('function');
	eval('var execute = '+method);
        execute();
}

This is a simple yet easy way to execute functions on element click, that you might need to receive from the elements themselves.

My NEXT post will have great example of this.

HTML data attributes with jquery

I’ve been much happier coding client-side (remember, I am not Client Side Guy) since I’ve discovered the data attribute specifications in HTML5. With these new data attributes you can add custom attributes and values to html tags and still have them be valid!

<div id="myDiv" data-foo="bar" >

This is very nice since you can attach alot of useful data right to a tag that would make sense to hold that data. HTML very much striving to be more like XML in this regard. It’s nice to leave it open-ended with a wildcard so we are able to use whatever terminology after “data-” On top of all this, newer versions of Jquery give you an incredibly easy way to grab that data to pass and use to your needs in javascript.

var getVar = $("#myDiv").data("foo");
alert(getVar);

The above piece of code finds the data-foo attribute very easily and our alert would respond with the attached value: “bar”.

This has really changed my client side coding and helps make more sense to those that aren’t as comfortable in code to understand. No more dummy elements to pass around values for me!

Parsing jOrgCharts into JSON calls

Ok so as the brilliant Jeremiah Sandahl has posted earlier, you can make some pretty brilliant hierarchy charts using the plugin jOrgChart.js . You can read his post on Visualizing Hierarchy with jQuery.

 

Now that you know how to make brilliant charts, what do you do if you want to make changes? We found ourselves needing just that. Here is my blog on how we parsed jOrgCharts into JSON calls.

Step 1:

Make your jOrgChart. You can refer to Jeremiah’s post. One added input for charts that you plan to make changes to. The <ul> you are using as your reference list needs to be stored in a separate div than the chart itself. You will notice that for draggable lists where you drag one person to another column needs this in order to keep any changes.

Step 2:

Define what your database needs. Ours needed a userID and an array of their hierarchy. this formats to {user.key: “4″, user.hierarchy: “1.2.3.4″}

Basically this was the users ID followed by a list of who they report to, from the top level all the way down to themselves.

Now that I know that, I know just what I want my JSON to look like.

 

Step 3: parse the <ul> into an object. I creatively named mine “hierarchy”. Here is my code.

function makeArrays()
		{
			var hierarchy = [];
 
			$("#org li").each(function(){
				var uid = $(this).attr("id");
				var name = $(this).clone().children().remove().end().text();
				var hidSTR = "";
				var hid = $(this).parents("li");
				if(hid.length == 0) //If this object is the root user, substitute id with "orgName" so the DB knows it's the name of organization and not a user
				{
					hidSTR = "orgName ";
					var user = new Object();
					user.key = uid;
					user.hierarchy = hidSTR;
					hierarchy.push(user);
				}else{
					for(var i=hid.length-1; i>=0; i--)
					{
						if(i != hid.length-1)
						{
							hidSTR = hidSTR+hid[i].id+".";
						}else{
							hidSTR = hidSTR+""+hid[i].id;
						}
					}
				var user = new Object();
					user.key = uid;
					user.hierarchy = hidSTR;
					hierarchy.push(user);
				}
			});
			saveArray(hierarchy);
 
		}

Ok so its pretty clear a lot went on there. Some things we needed were to substitute the organizationID with “orgName” so that our DB knew it wasn’t a user. We also did a reverse for each loop that saves from the bottom of the list all the way to it’s top parents. You might need to play around with some of the object paths according to how your list was built.

 

Now the last executable line of code sends the object to a function called “saveArray”. This is the actual JSON post that sends it to the DB for preservation. Here is that code.

function saveArray(hierarchy){
	var url = urlYouSendObjectTo; 
	$.ajax({
            url: url,
            type: 'POST',
            contentType: 'application/json',
            data:  JSON.stringify(hierarchy),
            dataType: 'json',
			success: function(data){
				alert("this has been successful");
				}
        });
 
}

This function sends the hierarchy object to “url” which is wherever you need your post to go to, and then alerts success once it gets a good response from your server.

This is my crash course in parsing jOrgCharts into JSON. Thank you for your time!