SlideShare a Scribd company logo
1 of 48
Download to read offline
JAVASCRIPT
     &
 WORDPRESS
AVINASH KUNDALIYA (@HARDFIRE)
           <3 JS & PHP
IS JAVASCRIPT
IMPORTANT ??
USED BY 92.3% SITES
 OCTOBER 2012 - W3TECHS.COM
>80% RELY FOR IMPORTANT FUNCTIONALITY
UBIQUITOUS.
CAN MAKE SITE SLOW
  IF DONE THE WRONG WAY
CAN MAKE SITE UNUSABLE
  IF DONE TOTALLY THE WRONG WAY
I AM CONVINCED !!
WE SHOULD USE JS, THE RIGHT WAY
JAVASCRIPT
SOME DIFFERENTIATING PARTS
VAR
GLOBAL SCOPE BY DEFAULT
a=5;
function say() {
    a=3;
    console.log(a);
}
say();
console.log(a);

3
3 // whoa!
USE VAR KEYWORD
a=5;
function say() {
    var a=3;
    console.log(a);
}
say();
console.log(a);

3
5 // thank god! :D
HOISTING
   var val = 'namaste';
   (function() {
     console.log(val); // namaste
   })();

   var val = 'namaste';
   (function() {
     console.log(val); // undefined
     var val = 'ola!';
   })();


Wherever i define my variable, the initialization will be *hoisted*
                          to the top.
THIS
Elsewhere : current object instantiated by the class
    JS : depends on how the function is called.
     this refers to the owner of the function
THIS : WINDOW ( FUNCTION CALL )
function what_is_this() {
    console.log(this);
}
what_is_this(); //window
THIS : OBJECT ( OBJECT METHOD )
var thisObject = {
    thisFunc: function(){
        console.log(this);
    }
}
thisObject.thisFunc(); //thisObject
THIS : OBJECT ( CONSTRUCTING OBJECTS USING NEW )
function WordCamp(year){
    this.year = year;
    this.yellOut = function(){
        console.log("Yay! it is WC "+ this.year);
    }
}
var wc2012 = new WordCamp(2012);
wc2012.yellOut(); // Yay! it is WC 2012




var wc2011 = WordCamp(2011);
wc2012.yellOut(); // Undefined
yellOut(); // Yay! it is WC 2011
FUNCTIONS : FIRST CLASS
FUNCTION DECLARATION
function say() {
    var a=3;
    console.log(a);
}
say();




                        FUNCTION EXPRESSION
var say = function(){
    var a=3;
    console.log(a);
}
say();
function say(func) {
    var a=3;
    func(a);
}
say(console.log);


                       SEE, I CAN PASS FUNCTIONS
function say(func) {
    var a=3;
    func(a);
}
say(function(name){alert(name)});


                 EVEN FUNCTIONS WITHOUT A NAME
CODE TWISTERS
function foo(){
    function bar() {
        return 3;
    }
    return bar();
    function bar() {
        return 8;
    }
}
alert(foo());


                          Output : 8
CODE TWISTERS
 function foo(){
     var bar = function() {
         return 3;
     };
     return bar();
     var bar = function() {
         return 8;
     };
 }
 alert(foo());


                                 Output : 3
Code examples from http://javascriptweblog.wordpress.com/
THINGS MIGHT JUST GO WRONG
function getTenFunctionsBad() {
  var result = [];
  for (var i = 0; i < 10; i++) {
    result.push(function () {
      return i;
    });
  }
  return result;    }
var functionsBad = getTenFunctionsBad();
for (var i = 0; i < 10; i++) {
  console.log(functionsBad[i]());   }

10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10
BUT WE CAN FIX THEM
function getTenFunctions() {
  var result = [];
  for (var i = 0; i < 10; i++) {
    result.push((function (i) {
      return function () {
        return i;
      }
    })(i));     }
  return result;     }
var functions = getTenFunctions();
for (var i = 0; i < 10; i++) {
  console.log(functions[i]());     }
0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9
OK! LET'S TALK ABOUT WORDPRESS
add_action('wp_head', 'add_my_script');

function add_my_script() {
?>
<script type="text/javascript"
        src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/jquery.js"></sc
ript>

<script type="text/javascript"
        src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/my-script.js"><
/script>

<?php
}
LET'S DO IT LIKE THE PRO'S
    wp_register_script
    wp_deregister_script
    wp_enqueue_script
    wp_dequeue_script
WP_REGISTER_SCRIPT                @COD EX


                    Yo WP! Remember this script

(
$handle, //name of the script
$src, // url to script
$deps, // array of dependencies
$ver, //version of code
$in_footer // place in footer?
);
WP_REGISTER_SCRIPT - EXAMPLE
wp_register_script (
  'mytheme-custom', // handle WP will know JS by
  get_template_directory_uri() . '/js/custom.js',
  array('jquery'), // requires jQuery
  1.0, // version 1.0
  true // can load in footer
);


              Don't hardcode. Use plugins_url or
               get_template_directory_uri

                Many predefined libraries @codex
WP_DEREGISTER_SCRIPT                       @COD EX


                   Yo WP! forget about this script
wp_deregister_script('jquery');
WP_ENQUEUE_SCRIPT                @COD EX


             Yo WP! Please put the script in my page

wp_enqueue_script( $handle , $src , $deps ,
                    $ver , $in_footer );
A LITTLE COMPLEX EXAMPLE
function my_scripts_method() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/
jquery.min.js');
    wp_enqueue_script( 'jquery' );
}

add_action('wp_enqueue_scripts', 'my_scripts_method');


Use jQuery from google CDN instead of WordPress local
WP_DEQUEUE_SCRIPT           @COD EX


Hey WP! Someone put this script in my page, remove it please
  wp_dequeue_script($handle);
EXAMPLE
wp_register_script( 'jquery.flexslider',
    get_template_directory_uri().'/js/flex.js',
    array('jquery'), '1.7', true );
wp_register_script( 'home-page-slider',
     get_template_directory_uri().'/js/slider.js',
     array('jquery.flexslider'), '1.0', true );
if ( is_front_page() ) {
wp_enqueue_script('home-page-slider');
}
WP_LOCALIZE_SCRIPT                                 @COD EX


            Send data from WordPress to JavaScript
wp_localize_script( $handle, $object_name, $l10n );




                              SIMPLE EXAMPLE
wp_enqueue_script( 'some_handle' );
$translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_val
ue' => '10' );
wp_localize_script( 'some_handle', 'object_name', $translation_array );

console.log(object_name.some_string);
WP_LOCALIZE_SCRIPT EXAMPLE
wp_localize_script(
  'simplecatch_custom_slider', 'js_value',
  array(
    'transition_effect' => $transition_effect,
    'transition_delay' => $transition_delay,
    'transition_duration' => $transition_duration
  ));
AJAX IN WP
require_once( "../../../../wp-config.php" );
// or require_once( "../../../../wp-load.php" );




                  PLEASE DON'T TRY THIS AT HOME!
WP_AJAX_(ACTION)                     @COD EX

jQuery.post(
   MyAjax.ajaxurl,
   {
      'action':'add_foobar',
      'data':'foobarid'
   },
   function(response){
      alert('The server responded: ' + response);
   }
);
WP_AJAX_(ACTION)
add_action('wp_ajax_add_foobar',
            'prefix_ajax_add_foobar');

function prefix_ajax_add_foobar() {
   //Do Something really awesome here :)
   exit;
}
BUT WHY ?
SUMMING UP
var
this
functions awesomeness
use wordpress helper functions
WHAT NEXT
    "use strict"
    closures
    functional programming
    more quirks : JS Garden
“ Go make something awesome! ”
?
THE END :'(
- AVINASH KUNDALIYA / @HARDFIRE
Avinash Kundaliya: Javascript and WordPress

More Related Content

What's hot

Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012Rafael Felix da Silva
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneRafael Felix da Silva
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboardsDenis Ristic
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboardsDenis Ristic
 
How to develop modern web application framework
How to develop modern web application frameworkHow to develop modern web application framework
How to develop modern web application frameworktechmemo
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方techmemo
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkJeremy Kendall
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5mennovanslooten
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and othersYusuke Wada
 

What's hot (20)

Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012Desenvolvendo APIs usando Rails - Guru SC 2012
Desenvolvendo APIs usando Rails - Guru SC 2012
 
RSpec
RSpecRSpec
RSpec
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
Aplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com BackboneAplicacoes dinamicas Rails com Backbone
Aplicacoes dinamicas Rails com Backbone
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Excellent
ExcellentExcellent
Excellent
 
How to develop modern web application framework
How to develop modern web application frameworkHow to develop modern web application framework
How to develop modern web application framework
 
優しいWAFの作り方
優しいWAFの作り方優しいWAFの作り方
優しいWAFの作り方
 
Keeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro FrameworkKeeping it Small: Getting to know the Slim Micro Framework
Keeping it Small: Getting to know the Slim Micro Framework
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 

Viewers also liked

Viewers also liked (7)

The little-joomla-seo-book-v1
The little-joomla-seo-book-v1The little-joomla-seo-book-v1
The little-joomla-seo-book-v1
 
Reptile repro. and diseases
Reptile repro. and diseasesReptile repro. and diseases
Reptile repro. and diseases
 
Ecommerce webinar-oct-2010
Ecommerce webinar-oct-2010Ecommerce webinar-oct-2010
Ecommerce webinar-oct-2010
 
In the kitchen
In the kitchenIn the kitchen
In the kitchen
 
3 d design profile [aksatech]
3 d design profile  [aksatech]3 d design profile  [aksatech]
3 d design profile [aksatech]
 
Webmaster guide-en
Webmaster guide-enWebmaster guide-en
Webmaster guide-en
 
Present forms
Present formsPresent forms
Present forms
 

Similar to Avinash Kundaliya: Javascript and WordPress

ReactJs presentation
ReactJs presentationReactJs presentation
ReactJs presentationnishasowdri
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Nicolás Bouhid
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPFrameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPDan Jesus
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 

Similar to Avinash Kundaliya: Javascript and WordPress (20)

ReactJs presentation
ReactJs presentationReactJs presentation
ReactJs presentation
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
Intro to jquery
Intro to jqueryIntro to jquery
Intro to jquery
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPFrameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
 
symfony & jQuery (phpDay)
symfony & jQuery (phpDay)symfony & jQuery (phpDay)
symfony & jQuery (phpDay)
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 

More from wpnepal

Mahadev Subedi: WordPress Security & Defense Mechanism
Mahadev Subedi: WordPress Security & Defense MechanismMahadev Subedi: WordPress Security & Defense Mechanism
Mahadev Subedi: WordPress Security & Defense Mechanismwpnepal
 
Pankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPressPankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPresswpnepal
 
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...wpnepal
 
Ujwal Thapa: WordPress as a Blogging Platform
Ujwal Thapa: WordPress as a Blogging PlatformUjwal Thapa: WordPress as a Blogging Platform
Ujwal Thapa: WordPress as a Blogging Platformwpnepal
 
Yalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance MarketplacesYalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance Marketplaceswpnepal
 
Vinay Paudel: Optimizing and Speeding up a WordPress site
Vinay Paudel: Optimizing and Speeding up a WordPress siteVinay Paudel: Optimizing and Speeding up a WordPress site
Vinay Paudel: Optimizing and Speeding up a WordPress sitewpnepal
 
Sanjip Shah: Internationalizing and Localizing WordPress Themes
Sanjip Shah: Internationalizing and Localizing  WordPress ThemesSanjip Shah: Internationalizing and Localizing  WordPress Themes
Sanjip Shah: Internationalizing and Localizing WordPress Themeswpnepal
 
Utsav Singh Rathour: How, Why and Where to use WordPress multisite
Utsav Singh Rathour: How, Why and Where to use WordPress multisiteUtsav Singh Rathour: How, Why and Where to use WordPress multisite
Utsav Singh Rathour: How, Why and Where to use WordPress multisitewpnepal
 
Rabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPressRabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPresswpnepal
 
Roshan Bhattarai: Scaling WordPress for high traffic sites
Roshan Bhattarai: Scaling WordPress for high traffic sitesRoshan Bhattarai: Scaling WordPress for high traffic sites
Roshan Bhattarai: Scaling WordPress for high traffic siteswpnepal
 
Chandra Prakash Thapa: Make a WordPress Multisite in 20 mins
Chandra Prakash Thapa: Make a WordPress Multisite in 20 minsChandra Prakash Thapa: Make a WordPress Multisite in 20 mins
Chandra Prakash Thapa: Make a WordPress Multisite in 20 minswpnepal
 
Jimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina DesignJimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina Designwpnepal
 
Bigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPressBigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPresswpnepal
 
Kris Thapa: WP Ambulance
Kris Thapa: WP AmbulanceKris Thapa: WP Ambulance
Kris Thapa: WP Ambulancewpnepal
 
Chandra Maharzan: Making a successful career out of WordPress
Chandra Maharzan: Making a successful career out of WordPressChandra Maharzan: Making a successful career out of WordPress
Chandra Maharzan: Making a successful career out of WordPresswpnepal
 
Simple Contact Us Plugin Development
Simple Contact Us Plugin DevelopmentSimple Contact Us Plugin Development
Simple Contact Us Plugin Developmentwpnepal
 
WP Ambulance
WP AmbulanceWP Ambulance
WP Ambulancewpnepal
 
How to earn and maximize your earnings from your Blog - Pawan Agrawal
How to earn and maximize your earnings from your Blog - Pawan AgrawalHow to earn and maximize your earnings from your Blog - Pawan Agrawal
How to earn and maximize your earnings from your Blog - Pawan Agrawalwpnepal
 

More from wpnepal (18)

Mahadev Subedi: WordPress Security & Defense Mechanism
Mahadev Subedi: WordPress Security & Defense MechanismMahadev Subedi: WordPress Security & Defense Mechanism
Mahadev Subedi: WordPress Security & Defense Mechanism
 
Pankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPressPankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPress
 
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...
Jimba Tamang: 5 reasons why “Parallax Websites” are awesome and how to create...
 
Ujwal Thapa: WordPress as a Blogging Platform
Ujwal Thapa: WordPress as a Blogging PlatformUjwal Thapa: WordPress as a Blogging Platform
Ujwal Thapa: WordPress as a Blogging Platform
 
Yalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance MarketplacesYalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance Marketplaces
 
Vinay Paudel: Optimizing and Speeding up a WordPress site
Vinay Paudel: Optimizing and Speeding up a WordPress siteVinay Paudel: Optimizing and Speeding up a WordPress site
Vinay Paudel: Optimizing and Speeding up a WordPress site
 
Sanjip Shah: Internationalizing and Localizing WordPress Themes
Sanjip Shah: Internationalizing and Localizing  WordPress ThemesSanjip Shah: Internationalizing and Localizing  WordPress Themes
Sanjip Shah: Internationalizing and Localizing WordPress Themes
 
Utsav Singh Rathour: How, Why and Where to use WordPress multisite
Utsav Singh Rathour: How, Why and Where to use WordPress multisiteUtsav Singh Rathour: How, Why and Where to use WordPress multisite
Utsav Singh Rathour: How, Why and Where to use WordPress multisite
 
Rabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPressRabin Shrestha: Data Validation and Sanitization in WordPress
Rabin Shrestha: Data Validation and Sanitization in WordPress
 
Roshan Bhattarai: Scaling WordPress for high traffic sites
Roshan Bhattarai: Scaling WordPress for high traffic sitesRoshan Bhattarai: Scaling WordPress for high traffic sites
Roshan Bhattarai: Scaling WordPress for high traffic sites
 
Chandra Prakash Thapa: Make a WordPress Multisite in 20 mins
Chandra Prakash Thapa: Make a WordPress Multisite in 20 minsChandra Prakash Thapa: Make a WordPress Multisite in 20 mins
Chandra Prakash Thapa: Make a WordPress Multisite in 20 mins
 
Jimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina DesignJimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina Design
 
Bigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPressBigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPress
 
Kris Thapa: WP Ambulance
Kris Thapa: WP AmbulanceKris Thapa: WP Ambulance
Kris Thapa: WP Ambulance
 
Chandra Maharzan: Making a successful career out of WordPress
Chandra Maharzan: Making a successful career out of WordPressChandra Maharzan: Making a successful career out of WordPress
Chandra Maharzan: Making a successful career out of WordPress
 
Simple Contact Us Plugin Development
Simple Contact Us Plugin DevelopmentSimple Contact Us Plugin Development
Simple Contact Us Plugin Development
 
WP Ambulance
WP AmbulanceWP Ambulance
WP Ambulance
 
How to earn and maximize your earnings from your Blog - Pawan Agrawal
How to earn and maximize your earnings from your Blog - Pawan AgrawalHow to earn and maximize your earnings from your Blog - Pawan Agrawal
How to earn and maximize your earnings from your Blog - Pawan Agrawal
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 

Avinash Kundaliya: Javascript and WordPress

  • 1.
  • 2. JAVASCRIPT & WORDPRESS AVINASH KUNDALIYA (@HARDFIRE) <3 JS & PHP
  • 4. USED BY 92.3% SITES OCTOBER 2012 - W3TECHS.COM
  • 5. >80% RELY FOR IMPORTANT FUNCTIONALITY
  • 7. CAN MAKE SITE SLOW IF DONE THE WRONG WAY
  • 8.
  • 9. CAN MAKE SITE UNUSABLE IF DONE TOTALLY THE WRONG WAY
  • 10. I AM CONVINCED !! WE SHOULD USE JS, THE RIGHT WAY
  • 12. VAR
  • 13. GLOBAL SCOPE BY DEFAULT a=5; function say() { a=3; console.log(a); } say(); console.log(a); 3 3 // whoa!
  • 14. USE VAR KEYWORD a=5; function say() { var a=3; console.log(a); } say(); console.log(a); 3 5 // thank god! :D
  • 15. HOISTING var val = 'namaste'; (function() { console.log(val); // namaste })(); var val = 'namaste'; (function() { console.log(val); // undefined var val = 'ola!'; })(); Wherever i define my variable, the initialization will be *hoisted* to the top.
  • 16. THIS Elsewhere : current object instantiated by the class JS : depends on how the function is called. this refers to the owner of the function
  • 17. THIS : WINDOW ( FUNCTION CALL ) function what_is_this() { console.log(this); } what_is_this(); //window
  • 18. THIS : OBJECT ( OBJECT METHOD ) var thisObject = { thisFunc: function(){ console.log(this); } } thisObject.thisFunc(); //thisObject
  • 19. THIS : OBJECT ( CONSTRUCTING OBJECTS USING NEW ) function WordCamp(year){ this.year = year; this.yellOut = function(){ console.log("Yay! it is WC "+ this.year); } } var wc2012 = new WordCamp(2012); wc2012.yellOut(); // Yay! it is WC 2012 var wc2011 = WordCamp(2011); wc2012.yellOut(); // Undefined yellOut(); // Yay! it is WC 2011
  • 21. FUNCTION DECLARATION function say() { var a=3; console.log(a); } say(); FUNCTION EXPRESSION var say = function(){ var a=3; console.log(a); } say();
  • 22. function say(func) { var a=3; func(a); } say(console.log); SEE, I CAN PASS FUNCTIONS function say(func) { var a=3; func(a); } say(function(name){alert(name)}); EVEN FUNCTIONS WITHOUT A NAME
  • 23. CODE TWISTERS function foo(){ function bar() { return 3; } return bar(); function bar() { return 8; } } alert(foo()); Output : 8
  • 24. CODE TWISTERS function foo(){ var bar = function() { return 3; }; return bar(); var bar = function() { return 8; }; } alert(foo()); Output : 3 Code examples from http://javascriptweblog.wordpress.com/
  • 25. THINGS MIGHT JUST GO WRONG function getTenFunctionsBad() { var result = []; for (var i = 0; i < 10; i++) { result.push(function () { return i; }); } return result; } var functionsBad = getTenFunctionsBad(); for (var i = 0; i < 10; i++) { console.log(functionsBad[i]()); } 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10
  • 26. BUT WE CAN FIX THEM function getTenFunctions() { var result = []; for (var i = 0; i < 10; i++) { result.push((function (i) { return function () { return i; } })(i)); } return result; } var functions = getTenFunctions(); for (var i = 0; i < 10; i++) { console.log(functions[i]()); } 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9
  • 27. OK! LET'S TALK ABOUT WORDPRESS
  • 28. add_action('wp_head', 'add_my_script'); function add_my_script() { ?> <script type="text/javascript" src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/jquery.js"></sc ript> <script type="text/javascript" src="<?php bloginfo('wpurl'); ?>/wp-content/plugins/my-plugin/my-script.js">< /script> <?php }
  • 29.
  • 30. LET'S DO IT LIKE THE PRO'S wp_register_script wp_deregister_script wp_enqueue_script wp_dequeue_script
  • 31. WP_REGISTER_SCRIPT @COD EX Yo WP! Remember this script ( $handle, //name of the script $src, // url to script $deps, // array of dependencies $ver, //version of code $in_footer // place in footer? );
  • 32. WP_REGISTER_SCRIPT - EXAMPLE wp_register_script ( 'mytheme-custom', // handle WP will know JS by get_template_directory_uri() . '/js/custom.js', array('jquery'), // requires jQuery 1.0, // version 1.0 true // can load in footer ); Don't hardcode. Use plugins_url or get_template_directory_uri Many predefined libraries @codex
  • 33. WP_DEREGISTER_SCRIPT @COD EX Yo WP! forget about this script wp_deregister_script('jquery');
  • 34. WP_ENQUEUE_SCRIPT @COD EX Yo WP! Please put the script in my page wp_enqueue_script( $handle , $src , $deps , $ver , $in_footer );
  • 35. A LITTLE COMPLEX EXAMPLE function my_scripts_method() { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/ jquery.min.js'); wp_enqueue_script( 'jquery' ); } add_action('wp_enqueue_scripts', 'my_scripts_method'); Use jQuery from google CDN instead of WordPress local
  • 36. WP_DEQUEUE_SCRIPT @COD EX Hey WP! Someone put this script in my page, remove it please wp_dequeue_script($handle);
  • 37. EXAMPLE wp_register_script( 'jquery.flexslider', get_template_directory_uri().'/js/flex.js', array('jquery'), '1.7', true ); wp_register_script( 'home-page-slider', get_template_directory_uri().'/js/slider.js', array('jquery.flexslider'), '1.0', true ); if ( is_front_page() ) { wp_enqueue_script('home-page-slider'); }
  • 38. WP_LOCALIZE_SCRIPT @COD EX Send data from WordPress to JavaScript wp_localize_script( $handle, $object_name, $l10n ); SIMPLE EXAMPLE wp_enqueue_script( 'some_handle' ); $translation_array = array( 'some_string' => __( 'Some string to translate' ), 'a_val ue' => '10' ); wp_localize_script( 'some_handle', 'object_name', $translation_array ); console.log(object_name.some_string);
  • 39. WP_LOCALIZE_SCRIPT EXAMPLE wp_localize_script( 'simplecatch_custom_slider', 'js_value', array( 'transition_effect' => $transition_effect, 'transition_delay' => $transition_delay, 'transition_duration' => $transition_duration ));
  • 40. AJAX IN WP require_once( "../../../../wp-config.php" ); // or require_once( "../../../../wp-load.php" ); PLEASE DON'T TRY THIS AT HOME!
  • 41. WP_AJAX_(ACTION) @COD EX jQuery.post( MyAjax.ajaxurl, { 'action':'add_foobar', 'data':'foobarid' }, function(response){ alert('The server responded: ' + response); } );
  • 42. WP_AJAX_(ACTION) add_action('wp_ajax_add_foobar', 'prefix_ajax_add_foobar'); function prefix_ajax_add_foobar() { //Do Something really awesome here :) exit; }
  • 44. SUMMING UP var this functions awesomeness use wordpress helper functions
  • 45. WHAT NEXT "use strict" closures functional programming more quirks : JS Garden “ Go make something awesome! ”
  • 46. ?
  • 47. THE END :'( - AVINASH KUNDALIYA / @HARDFIRE