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

優しい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 Framework
Jeremy Kendall
 

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 (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

The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
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 Joomla
Luke Summerfield
 
Frameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHPFrameworks da nova Era PHP FuelPHP
Frameworks da nova Era PHP FuelPHP
Dan Jesus
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris 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 Mechanism
wpnepal
 
Pankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPressPankaj Agrawal: eLearning on WordPress
Pankaj Agrawal: eLearning on WordPress
wpnepal
 
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
 
Yalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance MarketplacesYalamber Subba: WordPress Jobs & Freelance Marketplaces
Yalamber Subba: WordPress Jobs & Freelance Marketplaces
wpnepal
 
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
wpnepal
 
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
wpnepal
 
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
wpnepal
 
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
wpnepal
 
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
wpnepal
 
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
wpnepal
 
Jimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina DesignJimba Tamang: Responsive and Retina Design
Jimba Tamang: Responsive and Retina Design
wpnepal
 
Bigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPressBigyan Ghimire: GovtPress
Bigyan Ghimire: GovtPress
wpnepal
 
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
wpnepal
 

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

Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 

Recently uploaded (20)

Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

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