Posts Tagged “JavaScript”

Embed a Fiddle

Posted on June 25th, 2014 by webninjataylor

<iframe src=”http://jsfiddle.net/USERNAME/FIDDLE/embedded/result,resources,html,css,js” width=”100%” height=”300″ frameborder=”0″ allowfullscreen=”allowfullscreen”></iframe>

jQuery: Working with JSON via AJAX

Posted on June 24th, 2014 by webninjataylor

JSON property keys are always in quotes, but not in JS XHR = XML HTTP Request CFM = Control Flow Management (ex. page loading and data loading asynchronously) $.ajax({    url: ”,    data: {‘myUrlParams’: ‘value’},    success: function(){…},    error: function(){…},    dataType: ‘json’ // use jsonp for cross-domain });

Creating a jQuery Plugin

Posted on June 24th, 2014 by webninjataylor

$.fn.makeTabsFor = function(){…};   // Create method $(tabs).makeTabsFor(content);   // Call method $.fn.makeTabsFor(content); // Call method when no selector is used When your plugin code gets called, it’s called in the context of the selected jQuery object, so the method “this” becomes the jQuery object itself.

jQuery Animations

Posted on June 24th, 2014 by webninjataylor

Animations initiated by the user should be quick while animations initiated by the website can be slower to draw attention Animations create ‘eye-light’ and affordance for a website Use the jQuery easings plugin (or jQuery UI) since jQuery only comes with swing and linear A common configuration of the method’s arguments is… The hash (aka object or properties […]

JavaScript: Things to Know in 2014

Posted on June 24th, 2014 by webninjataylor

Here’s a list I’ve compiled from interviews and articles of core JavaScript knowledge for 2014… Event delegation and bubbling Prototypes and inheritance Functions are first-class objects Modular JavaScript Constructor-based approach vs. mixins How to control “this” through bind, apply, and call Async code and how to manage it through things like promises and queues Code testing […]

The Proper Way to Add CSS and JS to a WordPress Theme

Posted on June 23rd, 2014 by webninjataylor

Add this to functions.php for JS and CSS.  Check out the WordPress Codex for available parameters and info on using the ‘$’ namespace for jQuery. <?php function wnt_styles(){ // STYLES wp_register_style(‘bootstrapcss’, get_template_directory_uri() . ‘/css/bootstrap.css’, array(), ‘20140529’, ‘all’ ); wp_enqueue_style(‘bootstrapcss’); } add_action(‘wp_enqueue_scripts’, ‘wnt_styles’); wp_enqueue_script(‘jquery’); // This is all that’s needed for jQuery since WordPress already has […]

JavaScript Partials

Posted on June 11th, 2014 by webninjataylor

Gratuitously copied from John Resig’s blog… Partially applying a function is a technique in which you can pre-fill-in arguments to a function before it is ever executed. In effect, partially applying a function returns a new function which you can call… String.prototype.csv = String.prototype.split.partial(/,\s*/); var results = “John, Resig, Boston”.csv(); alert( (results[1] == “Resig”) + […]

JavaScript Functions are First-class Objects

Posted on June 10th, 2014 by webninjataylor

This means that javascript functions are just a special type of object that can do all the things that regular objects can do.  Just like any other variable… A function is an instance of the Object type A function can have properties and has a link back to its constructor method You can store the […]

Tags:
Posted in Web ShotsComments Off on JavaScript Functions are First-class Objects

JavaScript Prototypes and Inheritance

Posted on June 10th, 2014 by webninjataylor

Objects have a built-in attribute called prototype who’s value is a pointer to another object, and can be declared when creating a new object with Object.create(myPrototypeReference). If an object is created using the convenience of an object literal var newObject = {property: ‘value‘} then the prototype is defaulted to Object.prototype. Overview Objects are pairs of keys and […]

Tags:
Posted in Web ShotsComments Off on JavaScript Prototypes and Inheritance

Event Binding Woes

Posted on June 9th, 2014 by webninjataylor

In addition to viewing current events bound to an object with … $._data( $(‘SELECTOR’)[0], ‘events’ ); …in the console.  I’ve discovered it is sometimes necessary to bind the event to a parent which already exists on the page as some scenarios don’t have all objects ready when the .ready() method is fired (*ahem* SharePoint, I’m […]

Sort Lists with JavaScript

Posted on September 18th, 2013 by webninjataylor

This solution requires jQuery and Underscore. var wnt = {}; wnt.sortList = { asc: function(sList){ sListItems = $(sList).find(‘li’); sListItems = _.sortBy(sListItems, function(item){ return $(item).text(); }); $(sList).html(sListItems); }, desc: function(sList){ sListItems = $(sList).find(‘li’); sListItems = _.sortBy(sListItems, function(item){ return $(item).text(); }).reverse(); $(sList).html(sListItems); } }; wnt.sortToggle = “asc”; $(‘ul’).click(function(){ wnt.sortList[wnt.sortToggle]($(this)); wnt.sortToggle===’asc’ ? wnt.sortToggle=”desc” : wnt.sortToggle=”asc”; }); Fiddle

Chrome Developer Tools: Saving JavaScript Edits

Posted on September 5th, 2013 by webninjataylor

You must do a right-click “Save As…” for saving to work locally. Then, subsequent edits may be saved with just “Save” or the keyboard shortcut https://developers.google.com/chrome-developer-tools/docs/authoring-development-workflow#save-as

JavaScript Prototyping Techniques

Posted on September 3rd, 2013 by webninjataylor

Prototyping via Constructor Functions /* Old way – awkward – exists for people used to classes */ // Create constructor function function Greeter(name){ this.name = name || ‘JohnDoe’; } // Attach to that constructor function’s prototype property Greeter.prototype.hello = function hello(){ return ‘Old Way = Hello, my name is ‘ + this.name; } // Instantiate […]

Count CSS Rules in Console

Posted on July 11th, 2013 by webninjataylor

In your console, type… var sheets = document.styleSheets; var rules = 0; for(i=0; i < sheets.length; i++){ if(sheets[i].cssRules !== null){ rules = rules + sheets[i].cssRules.length; } } console.log(‘Rules = ‘+rules); IE limits rules to 4,095.

Trigger Event in Plain JavaScript

Posted on June 10th, 2013 by webninjataylor

var elem = document.getElementById(‘myForm’); var event = new Event(‘submit’); elem.dispatchEvent(event);

JavaScript Unit Testing

Posted on May 22nd, 2013 by webninjataylor

Integration tests are for how users interact with an app, and unit tests are for small modules of code QUnit is a framework for writing JavaScript unit tests Simple Implementation Page (tests.php) … <link rel=”stylesheet” href=”css/qunit-1.11.0.css”> … <div id=”qunit”></div> <div id=”qunit-fixture”></div> … <script type=”text/javascript” src=”js/qunit-1.11.0.js”></script> <script type=”text/javascript” src=”js/tests.js”></script> tests.js test(“hello test”, function(){ ok( 1 == “1”, […]

Using Dispatch Tables to Avoid Conditionals in JavaScript

Posted on May 21st, 2013 by webninjataylor

function processUserInput(command) { switch (command) { case “north”: movePlayer(“north”); break; case “east”: movePlayer(“east”); break; case “south”: movePlayer(“south”); break; case “west”: movePlayer(“west”); break; case “look”: describeLocation(); break; case “backpack”: showBackpack(); break; } } Can be turned into… var commandTable = { north: function() { movePlayer(“north”); }, east: function() { movePlayer(“east”); }, south: function() { movePlayer(“south”); }, […]

Tags:
Posted in Web ShotsComments Off on Using Dispatch Tables to Avoid Conditionals in JavaScript

jQuery Chaining and .fail()

Posted on May 17th, 2013 by webninjataylor

Examples of using .fail() method to handle errors via chaining… onSubmitEmailForm: function(e) { e.preventDefault(); if (this.isValid(this.$emailForm)) { $.ajax({ type: ‘POST’, url: this.$emailForm.attr(‘action’), data: this.$emailForm.serialize() }).done(_.bind(function(response) { this.$container.hide(); this.$(‘.email-success’).show(); PubSub.trigger(‘uotrack’, ‘UtilityBarShareEmail’); }, this)).fail(_.bind(function(response){ alert(“Your text did not match the image.”); }, this)); } }, $.get(“test.php”) .done(function(){ alert(“$.get succeeded”); }) .fail(function(){ alert(“$.get failed!”); }); Resources jQuery API

JavaScript Callback Functions

Posted on May 14th, 2013 by webninjataylor

 Functions are objects A Function object contains a string which contains the Javascript code of the function For Javascript, the distinction between code and data is sometimes blurred One benefit of this function-as-object concept is that you can pass code to another function in the same way you would pass a regular variable or object […]

Responsive Menu Layout

Posted on May 14th, 2013 by webninjataylor

Define CSS breakpoints with media queries (ie. button for small width vs. full menu for wider) Hide button for wider, thus… The JS can react when the button is visible or not for appropriate device behaviors Resources Behavioral Breakpoints