jquery4u.com - Archives (juin 2016)

1 jQuery Fan Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets.

Le: 29 06 2016 à 22:00 Auteur: Simon Codrington

You've probably worked on interactive components before, like sliders, galleries or interactive forms. While you might be creating these on a site-by-site basis, one great time saver is to build your functionality as a jQuery plugin to speed up your development.

jQuery plugins let you define your functionality once and then drop it into your projects as needed, getting you up and running faster.

We're going to look at how to build your own jQuery plugin. We'll look at all the areas you need to know to get you up and running building plugins in no time.

We'll be using a plugin I've created called fancytoggle to showcase the different parts of a plugin. It's a simple plugin for toggling the visibility of nested elements, such as list items, to create accordion-style widgets for things like FAQs. The overall idea is about the concepts of plugins, but this example should help you see how it all works in practice.

See the Pen FancyToggle by SitePoint (@SitePoint) on CodePen.

A Plugin Approach: The Advantages

The core concept here is to create something extensible that you can add to your projects to give you quick functionality. jQuery's plugin functionality simplifies the process of building reusable code.

One of the strengths of these plugins is that they let the developer define several options that can be used to customize the functionality. You might create several options that change the way your plugin operates entirely, or you might just define a few to give the user a bit more control for styling or layout. With plugins, this choice will be up to you.

Developing jQuery Plugins

Let's run through the steps needed to register a new jQuery plugin. We'll use our example plugin, fancyToggle, so you can see how it's all put together.

Creating our function with $.fn

jQuery plugins work by registering a function with the name you want to call to trigger your plugin (for example, you call jQuery's inbuilt .width() or .height() functions when you want the width / height returned)

We attach our function to jQuery's $.fn object to make it available to the global $ object. This registers our function and lets it be called on objects or selections.

//registering our function
$.fn.fancytoggle = function(){
  // ...
};

That's all there is to it! You now have a new method you can call from jQuery's $ object. Right now, it won't do anything, but you can call this method wherever you like, for example on a selector:

//Call fancytoggle on this element
$('.my-element').fancytoggle(); 

You can register as many functions as you want with $.fn, however its good practice to avoid registering more than one function unless the plugin does distinctly different tasks.

Multiple collections and looping

An important thing to understand is that when your plugin is called it might be applying itself to either a single element or to several. For example with our plugin, if we are applying fancytoggle() to several different items we will have a collection to process within our function.

To process each element we just need to loop through the collection using jQuery's $.each function:

Continue reading %Introduction to Developing jQuery Plugins%

Le: 23 06 2016 à 23:00 Auteur: James Hibbard

If you're developing a web-based aplication and are trying to load data from a domain which is not under your control, the chances are that you've seen the following message in your browser's console:

XMLHttpRequest cannot load http://external-domain/service. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://my-domain' is therefore not allowed access.

In this article, we'll look at what causes this error and how we can get around it by using jQuery and JSONP to make a cross-domain Ajax call.

Same-origin Policy

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, however they're restricted in what they can do by the same origin-policy. This is an important concept in the browser security model and dictates that a web browser may only allow scripts on page A to access data on page B if these two pages have the same origin. The origin of a page is defined by its protocol, host and port number. For example the origin of this page is 'https', 'www.sitepoint.com', '80'.

The same-origin policy is a saftey mechanism. It prevents scripts from reading data from your domain and sending it to their servers. If we didn't have this, it would be easy for a malicious website to grab your session information to another site (such as Gmail or Twitter) and execute actions on your behalf. Unfortunately, it also causes the error we see above and often poses a headache for developers trying to accomplish a legitimate task.

A failing example

Let's look at what doesn't work. Here's a JSON file residing on a different domain which we would like to load using jQuery's getJSON method.

$.getJSON(
  "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
  function(json) { console.log(json); }
);

If you try that out in your browser with an open console, you will see a message similar to the one above. So what can we do?

A Possible Workaround

Luckily, not everything is affected by the same-origin policy. For example, it is quite possible to load an image or a script from a different domain into your page—this is exactly what you are doing when you include jQuery (for example) from a CDN.

This means that we are able to create a <script> tag, set the src attribute to that of our JSON file and inject it into the page.

var script = $("<script />", {
    src: "http://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-1.json",
    type: "application/json"
  }
);

$("head").append(script);

Although that works, it doesn't help us much, as we have no way of getting at the data it contains.

Enter JSONP

JSONP (which stands for JSON with Padding) builds on this technique and provides us with a way to access the returned data. It does this by having the server return JSON data wrapped in a function call (the "padding") which can then be interpreted by the browser. This function must be defined in the page evaluating the JSONP response.

Continue reading %jQuery’s JSONP Explained with Examples%