SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
Using YUI Dom

to tame the Browser

       Christian Heilmann
  Yahoo! F2E Summit Asia 2007
Quick reminder

• Development according to web standards
  means first and foremost separation.
• Specifically separation of web
  development layers.
addClass batch generateId get
getAncestorBy getAncestorByClassName
getAncestorByTagName getChildren
getChildrenBy getClientHeight
getClientWidth getDocumentHeight
getDocumentScrollLeft
getDocumentScrollTop getDocumentWidth
getElementsBy getElementsByClassName
getFirstChild getFirstChildBy
getLastChild getLastChildBy
getNextSibling getNextSiblingBy
getPreviousSibling getPreviousSiblingBy
getRegion getStyle getViewportHeight
getViewportWidth getX getXY getY
hasClass inDocument insertAfter
insertBefore isAncestor removeClass
replaceClass setStyle setX setXY setY
Use cases for the DOM utility

•   Using CSS Classes
•   Getting elements from the DOM
•   Using the browser dimensions
•   Using element dimensions
•   Styling elements
Using CSS Classes


• addClass()
• removeClass()
• hasClass()
• replaceClass()
• getElementsByClassName()
Why?
Why?

• CSS is the supercharged DOM Scripting.
• CSS is much closer connected to the
  HTML
• Therefore it is more likely to change at the
  same time.
• I hate loops.
Why?

• CSS is the supercharged DOM Scripting.
• CSS is much closer connected to the
  HTML
• Therefore it is more likely to change at the
  same time.
• I hate loops.
Why?

• CSS is the supercharged DOM Scripting.
• CSS is much closer connected to the
  HTML
• Therefore it is more likely to change at the
  same time.
• I hate loops.
Why?

• CSS is the supercharged DOM Scripting.
• CSS is much closer connected to the
  HTML
• Therefore it is more likely to change at the
  same time.
• I hate loops.
Example:

Hiding all “trigger” links in a main section
when JS is available.
Example:
var main = document.getElementById('main');
if(main){
  var triggers = main.getElementsByTagName('a');
  for(var i=0,j=triggers.length;i<j;i++){
    if(triggers[i].className === 'trigger'){
      triggers[i].style.display = 'none';
    }
  }
}
Example:
var main = document.getElementById('main');
if(main){
  var triggers = main.getElementsByTagName('a');
  for(var i=0,j=triggers.length;i<j;i++){
    if(triggers[i].className === 'trigger'){
      triggers[i].style.display = 'none';
    }
  }
}


display:none is a bad plan!
Example:
var main = document.getElementById('main');
if(main){
  var triggers = main.getElementsByTagName('a');
  for(var i=0,j=triggers.length;i<j;i++){
    if(triggers[i].className === 'trigger'){
      triggers[i].style.display = 'none';
    }
  }
}


Off-left is better.
Example:
var main = document.getElementById('main');
if(main){
  var triggers = main.getElementsByTagName('a');
  for(var i=0,j=triggers.length;i<j;i++){
    if(triggers[i].className === 'trigger'){
      triggers[i].style.position = 'absolute';
      triggers[i].style.left = '-6000px';
    }
  }
}
Magic JavaScript Pixy Solution

$('#main a.trigger').hide();
My fave:

document.body.className = 'js';

// or
var b = document.body;
var bc = b.className;
b.className = bc ? bc + ' js' :
'js';
Getting elements from the DOM

• inDocument()
• isAncestor()
• getElementsByClassName
• getElementsBy
• get
• batch
Using the browser dimensions

• getViewportWidth()
• getViewportHeight()
• getDocumentWidth()
• getDocumentHeight()
Using element dimensions

• getX(), getY(), getXY()
• setX(), setY(), setXY()
• getRegion()
 – Region union
 – Region intersect
 – Region contains
Using element dimensions
Using element dimensions

• Each of these methods can take an ID, a
  reference of an HTMLelement or an array
  of elements as the parameter.
• This allows you to easily access a lot of
  elements.
Using element dimensions

• The Dom utility does not care if the
  element is positioned absolute, relative or
  static.
• It also sorts out differences in render mode
  for you.
• However, each element needs to be part
  of the Dom and not hidden with
  display:none!
Using element dimensions

• The get and set methods of x and y are
  very straight forward.
• They return the left, the top or both values
  in pixels or an array with this data for each
  element you parsed in.
• You can also set the position in pixels with
  the setter methods.
Using element dimensions

var xy =
  YAHOO.util.Dom.getXY('hd');
// = [128, 0];
YAHOO.util.Dom.setXY('hd',[128,-
  10]);
// shifts header 10 pixels up
Using element dimensions

• By using the getRegion() method you
  can read out the screen estate the
  element occupies.
• This is incredibly useful for positioning
  elements or avoiding overlap.
• The return is an object with several
  properties.
Using element dimensions
var h =
  YAHOO.util.Dom.getRegion('hd');
// h =
// {0:128
// 1:0,
// top:0,
// right:878,
// bottom:79,
// left:128}
Using element dimensions

• top, left, right, bottom are the pixel
  locations on the page.
• There are shortcuts for left and top named
  0 and 1 to allow for compatibility with
  setX,setY and setXY.
Using element dimensions

• Using these properties you can also
  calculate the dimensions of the element.
• Simply subtract left from right for the width.
• And top from bottom for the height.
Using element dimensions

• The Region() component does a lot
  more for you though.
• By calculating the region occupied by two
  elements, you can find out:
  – if one element contains the other
  – how big the area containing both of them is
    and
  – if and where they intersect
Using element dimensions
YD = YAHOO.util.Dom;
reg1 = YD.getRegion('r1');
reg2 = YD.getRegion('r2');
contains = reg1.contains(reg2);




                     Region #1    Region #2
Using element dimensions
YD = YAHOO.util.Dom;
reg1 = YD.getRegion('r1');
reg2 = YD.getRegion('r2');
contains = reg1.contains(reg2);

          false


                     Region #1    Region #2
Using element dimensions
YD = YAHOO.util.Dom;
reg1 = YD.getRegion('r1');
reg2 = YD.getRegion('r2');
contains = reg1.contains(reg2);




                        Region #1

                              Region #2
Using element dimensions
YD = YAHOO.util.Dom;
reg1 = YD.getRegion('r1');
reg2 = YD.getRegion('r2');
contains = reg1.contains(reg2);

          true

                        Region #1

                              Region #2
Using element dimensions
YD =   YAHOO.util.Dom;
reg1   = YD.getRegion('r1');
reg2   = YD.getRegion('r2');
is =   reg1.intersect(reg2);



                         Region #1



                                     Region #2
Using element dimensions
YD =   YAHOO.util.Dom;
reg1   = YD.getRegion('r1');
reg2   = YD.getRegion('r2');
is =   reg1.intersect(reg2);



                         Region #1



                                     Region #2
Using element dimensions
YD =   YAHOO.util.Dom;
reg1   = YD.getRegion('r1');
reg2   = YD.getRegion('r2');
is =   reg1.union(reg2);



                         Region #1
                         Region #1



                                     Region #2
                                     Region #2
Using element dimensions
YD =   YAHOO.util.Dom;
reg1   = YD.getRegion('r1');
reg2   = YD.getRegion('r2');
is =   reg1.union(reg2);



                         Region #1
                         Region #1



                                     Region #2
                                     Region #2
Styling elements

• getStyle()
• setStyle()
Styling Elements

• You might wonder why you’d need these
  two methods as seemingly
  element.style.property = value
  would do the same.
• The two methods however work around
  several browser problems and differences
  between computedStyle and
  currentStyle.
Styling Elements

• The other benefit is that you can use the
  CSS selector names instead of the
  camelCased JavaScript ones.
• Furthermore you can use the opacity
  property without needing to branch for
  different browsers.
CSS normalization

obj.style.marginTop = '10px';

               vs.

YAHOO.util.Dom.setStyle(obj,
'margin-top','10px');
CSS normalization

• Furthermore, opacity is not a nightmare
  any longer:

YAHOO.util.Dom.setStyle(obj, 'opacity','.2');
CSS normalization

• And last but not least, float can be
  used:
YAHOO.util.Dom.setStyle(obj, 'float','left');
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
saydin_soft
 

Was ist angesagt? (11)

Road to react hooks
Road to react hooksRoad to react hooks
Road to react hooks
 
08 Queries
08 Queries08 Queries
08 Queries
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
Designing Immutability Data Flows in Ember
Designing Immutability Data Flows in EmberDesigning Immutability Data Flows in Ember
Designing Immutability Data Flows in Ember
 
Deep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerViewDeep Dive Into LayoutManager for RecyclerView
Deep Dive Into LayoutManager for RecyclerView
 
2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux2018 02-22 React, Redux & Building Applications that Scale | Redux
2018 02-22 React, Redux & Building Applications that Scale | Redux
 
Working With JQuery Part1
Working With JQuery Part1Working With JQuery Part1
Working With JQuery Part1
 
informatics practices practical file
informatics practices practical fileinformatics practices practical file
informatics practices practical file
 
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
SenchaCon 2016: Add Magic to Your Ext JS Apps with D3 Visualizations - Vitaly...
 
Ms Ajax Dom Element Class
Ms Ajax Dom Element ClassMs Ajax Dom Element Class
Ms Ajax Dom Element Class
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 

Andere mochten auch (8)

Integrating Technology Using Digital Presentations
Integrating Technology Using Digital PresentationsIntegrating Technology Using Digital Presentations
Integrating Technology Using Digital Presentations
 
Pp Under Consturction
Pp Under ConsturctionPp Under Consturction
Pp Under Consturction
 
Put the Ease in Papers, Please!
Put the Ease in Papers, Please!Put the Ease in Papers, Please!
Put the Ease in Papers, Please!
 
Al Den Presentation
Al Den PresentationAl Den Presentation
Al Den Presentation
 
Integrating Technology Using Digital Presentations
Integrating Technology Using Digital PresentationsIntegrating Technology Using Digital Presentations
Integrating Technology Using Digital Presentations
 
Put the ease in papers, please!
Put the ease in papers, please!Put the ease in papers, please!
Put the ease in papers, please!
 
Dia Biblia
Dia BibliaDia Biblia
Dia Biblia
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Ähnlich wie Taming the browser with the YUI Dom Component

Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
nikhilyagnic
 
the next web now
the next web nowthe next web now
the next web now
zulin Gu
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
Wildan Maulana
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
gerbille
 

Ähnlich wie Taming the browser with the YUI Dom Component (20)

Js info vis_toolkit
Js info vis_toolkitJs info vis_toolkit
Js info vis_toolkit
 
Fact, Fiction, and FP
Fact, Fiction, and FPFact, Fiction, and FP
Fact, Fiction, and FP
 
the next web now
the next web nowthe next web now
the next web now
 
Using ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript ProjectUsing ReasonML For Your Next JavaScript Project
Using ReasonML For Your Next JavaScript Project
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
jQuery : Events are where it happens!
jQuery : Events are where it happens!jQuery : Events are where it happens!
jQuery : Events are where it happens!
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 
Webgl para JavaScripters
Webgl para JavaScriptersWebgl para JavaScripters
Webgl para JavaScripters
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Design Patterns for Tablets and Smartphones
Design Patterns for Tablets and SmartphonesDesign Patterns for Tablets and Smartphones
Design Patterns for Tablets and Smartphones
 
Utilising the data attribute
Utilising the data attributeUtilising the data attribute
Utilising the data attribute
 
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
 
How to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in RHow to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in R
 
COLLADA & WebGL
COLLADA & WebGLCOLLADA & WebGL
COLLADA & WebGL
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Building Robust jQuery Plugins
Building Robust jQuery PluginsBuilding Robust jQuery Plugins
Building Robust jQuery Plugins
 
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid ThemRedux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
Redux "Bad" Practices - A List of 13 Bad Practices and How to Avoid Them
 

Mehr von Christian Heilmann

The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)
Christian Heilmann
 

Mehr von Christian Heilmann (20)

Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019
 
Hinting at a better web
Hinting at a better webHinting at a better web
Hinting at a better web
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
 
Seven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC OsloSeven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC Oslo
 
Artificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynoteArtificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynote
 
Killing the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynoteKilling the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynote
 
Progressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays FinlandProgressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays Finland
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
 
Five ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developerFive ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developer
 
Taking the P out of PWA
Taking the P out of PWATaking the P out of PWA
Taking the P out of PWA
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
 
You learned JavaScript - now what?
You learned JavaScript - now what?You learned JavaScript - now what?
You learned JavaScript - now what?
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
 
Progressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReachProgressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReach
 
Progressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worldsProgressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worlds
 
Non-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humansNon-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humans
 
Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center
 
CSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. ControlCSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. Control
 
Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017
 
The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Taming the browser with the YUI Dom Component

  • 1. Using YUI Dom to tame the Browser Christian Heilmann Yahoo! F2E Summit Asia 2007
  • 2. Quick reminder • Development according to web standards means first and foremost separation. • Specifically separation of web development layers.
  • 3. addClass batch generateId get getAncestorBy getAncestorByClassName getAncestorByTagName getChildren getChildrenBy getClientHeight getClientWidth getDocumentHeight getDocumentScrollLeft getDocumentScrollTop getDocumentWidth getElementsBy getElementsByClassName getFirstChild getFirstChildBy getLastChild getLastChildBy getNextSibling getNextSiblingBy getPreviousSibling getPreviousSiblingBy getRegion getStyle getViewportHeight getViewportWidth getX getXY getY hasClass inDocument insertAfter insertBefore isAncestor removeClass replaceClass setStyle setX setXY setY
  • 4. Use cases for the DOM utility • Using CSS Classes • Getting elements from the DOM • Using the browser dimensions • Using element dimensions • Styling elements
  • 5. Using CSS Classes • addClass() • removeClass() • hasClass() • replaceClass() • getElementsByClassName()
  • 7. Why? • CSS is the supercharged DOM Scripting. • CSS is much closer connected to the HTML • Therefore it is more likely to change at the same time. • I hate loops.
  • 8. Why? • CSS is the supercharged DOM Scripting. • CSS is much closer connected to the HTML • Therefore it is more likely to change at the same time. • I hate loops.
  • 9. Why? • CSS is the supercharged DOM Scripting. • CSS is much closer connected to the HTML • Therefore it is more likely to change at the same time. • I hate loops.
  • 10. Why? • CSS is the supercharged DOM Scripting. • CSS is much closer connected to the HTML • Therefore it is more likely to change at the same time. • I hate loops.
  • 11. Example: Hiding all “trigger” links in a main section when JS is available.
  • 12. Example: var main = document.getElementById('main'); if(main){ var triggers = main.getElementsByTagName('a'); for(var i=0,j=triggers.length;i<j;i++){ if(triggers[i].className === 'trigger'){ triggers[i].style.display = 'none'; } } }
  • 13. Example: var main = document.getElementById('main'); if(main){ var triggers = main.getElementsByTagName('a'); for(var i=0,j=triggers.length;i<j;i++){ if(triggers[i].className === 'trigger'){ triggers[i].style.display = 'none'; } } } display:none is a bad plan!
  • 14. Example: var main = document.getElementById('main'); if(main){ var triggers = main.getElementsByTagName('a'); for(var i=0,j=triggers.length;i<j;i++){ if(triggers[i].className === 'trigger'){ triggers[i].style.display = 'none'; } } } Off-left is better.
  • 15. Example: var main = document.getElementById('main'); if(main){ var triggers = main.getElementsByTagName('a'); for(var i=0,j=triggers.length;i<j;i++){ if(triggers[i].className === 'trigger'){ triggers[i].style.position = 'absolute'; triggers[i].style.left = '-6000px'; } } }
  • 16. Magic JavaScript Pixy Solution $('#main a.trigger').hide();
  • 17. My fave: document.body.className = 'js'; // or var b = document.body; var bc = b.className; b.className = bc ? bc + ' js' : 'js';
  • 18. Getting elements from the DOM • inDocument() • isAncestor() • getElementsByClassName • getElementsBy • get • batch
  • 19. Using the browser dimensions • getViewportWidth() • getViewportHeight() • getDocumentWidth() • getDocumentHeight()
  • 20. Using element dimensions • getX(), getY(), getXY() • setX(), setY(), setXY() • getRegion() – Region union – Region intersect – Region contains
  • 22. Using element dimensions • Each of these methods can take an ID, a reference of an HTMLelement or an array of elements as the parameter. • This allows you to easily access a lot of elements.
  • 23. Using element dimensions • The Dom utility does not care if the element is positioned absolute, relative or static. • It also sorts out differences in render mode for you. • However, each element needs to be part of the Dom and not hidden with display:none!
  • 24. Using element dimensions • The get and set methods of x and y are very straight forward. • They return the left, the top or both values in pixels or an array with this data for each element you parsed in. • You can also set the position in pixels with the setter methods.
  • 25. Using element dimensions var xy = YAHOO.util.Dom.getXY('hd'); // = [128, 0]; YAHOO.util.Dom.setXY('hd',[128,- 10]); // shifts header 10 pixels up
  • 26. Using element dimensions • By using the getRegion() method you can read out the screen estate the element occupies. • This is incredibly useful for positioning elements or avoiding overlap. • The return is an object with several properties.
  • 27. Using element dimensions var h = YAHOO.util.Dom.getRegion('hd'); // h = // {0:128 // 1:0, // top:0, // right:878, // bottom:79, // left:128}
  • 28. Using element dimensions • top, left, right, bottom are the pixel locations on the page. • There are shortcuts for left and top named 0 and 1 to allow for compatibility with setX,setY and setXY.
  • 29. Using element dimensions • Using these properties you can also calculate the dimensions of the element. • Simply subtract left from right for the width. • And top from bottom for the height.
  • 30. Using element dimensions • The Region() component does a lot more for you though. • By calculating the region occupied by two elements, you can find out: – if one element contains the other – how big the area containing both of them is and – if and where they intersect
  • 31. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); contains = reg1.contains(reg2); Region #1 Region #2
  • 32. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); contains = reg1.contains(reg2); false Region #1 Region #2
  • 33. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); contains = reg1.contains(reg2); Region #1 Region #2
  • 34. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); contains = reg1.contains(reg2); true Region #1 Region #2
  • 35. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); is = reg1.intersect(reg2); Region #1 Region #2
  • 36. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); is = reg1.intersect(reg2); Region #1 Region #2
  • 37. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); is = reg1.union(reg2); Region #1 Region #1 Region #2 Region #2
  • 38. Using element dimensions YD = YAHOO.util.Dom; reg1 = YD.getRegion('r1'); reg2 = YD.getRegion('r2'); is = reg1.union(reg2); Region #1 Region #1 Region #2 Region #2
  • 40. Styling Elements • You might wonder why you’d need these two methods as seemingly element.style.property = value would do the same. • The two methods however work around several browser problems and differences between computedStyle and currentStyle.
  • 41. Styling Elements • The other benefit is that you can use the CSS selector names instead of the camelCased JavaScript ones. • Furthermore you can use the opacity property without needing to branch for different browsers.
  • 42. CSS normalization obj.style.marginTop = '10px'; vs. YAHOO.util.Dom.setStyle(obj, 'margin-top','10px');
  • 43. CSS normalization • Furthermore, opacity is not a nightmare any longer: YAHOO.util.Dom.setStyle(obj, 'opacity','.2');
  • 44. CSS normalization • And last but not least, float can be used: YAHOO.util.Dom.setStyle(obj, 'float','left');