### Install with Composer Source: https://github.com/masterminds/html5-php/wiki/Installation Add the masterminds/html5 package to your composer.json file to install using Composer. This is the recommended installation method. ```json { "require" : { "masterminds/html5": "dev-master" } } ``` -------------------------------- ### Install HTML5-PHP with Composer Source: https://github.com/masterminds/html5-php/blob/master/README.md Install the HTML5-PHP library using Composer by adding it to your composer.json file or by using the require command. ```json { "require" : { "masterminds/html5": "^2.0" }, } ``` ```bash composer require masterminds/html5 ``` -------------------------------- ### HTML Document with Processor Instruction Source: https://github.com/masterminds/html5-php/wiki/Processor-Instructions Example of an HTML document containing a processor instruction. ```html ``` -------------------------------- ### Setup Email Subscriber Widget Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Configures the RequireJS module for the email subscriber widget and sets up its options. Use this to initialize the subscriber form on your page. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'smarter-living-form-only', productCode: 'SL', elementToHideOnSubscribe: '.nythp-smarter-living-formonly-email-promo', text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get Smarter Living by email', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get Smarter Living by email'} }); setTimeout(function(){ var widget = document.getElementById('smarter-living-form-only'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Example HTML5 Parser Error Output Source: https://github.com/masterminds/html5-php/wiki/Parser-Errors This is an example of the output format for parser errors when no DOCTYPE is specified. ```text Array ( [0] => Line 0, Col 0: No DOCTYPE specified. ) ``` -------------------------------- ### Setup Email Subscriber Widget (Europe Edition) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Configures and sets up an email subscriber widget for the Europe Edition. It dynamically adjusts UI elements and event listeners based on user interaction and subscription status. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'morning-briefing-widget-au', productCode: 'MBAU', /* elementToHideOnSubscribe: '.nythp-morning-briefing-email-promo', */ text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get the Morning Briefing by email.', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get the Morning Briefing by email.'} }); setTimeout(function(){ var widget = document.getElementById('morning-briefing-widget-au'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Setup Email Subscriber Widget (Asia Edition) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Configures and sets up an email subscriber widget for the Asia Edition. It dynamically adjusts UI elements and event listeners based on user interaction and subscription status. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'morning-briefing-widget-as', productCode: 'MBAE', /* elementToHideOnSubscribe: '.nythp-morning-briefing-email-promo', */ text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get the Morning Briefing by email.', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get the Morning Briefing by email.'} }); setTimeout(function(){ var widget = document.getElementById('morning-briefing-widget-as'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Load HTML and Get Parser Errors in PHP Source: https://github.com/masterminds/html5-php/wiki/Parser-Errors Use this snippet to load an HTML string and retrieve any parser errors encountered. Ensure the HTML5 class is imported. ```php $html = <<< 'HERE' test

This is a test of the HTML5 parser.

HERE; $html5 = new HTML5(); $dom = $html5->loadHTML($html); print_r($html5->getErrors()); ``` -------------------------------- ### JavaScript Initialization and User Data Handling Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Initializes a signup promo view, handles user data readiness, and switches promotional text based on A/B test variants. It also tracks impressions and clicks. ```javascript require(['foundation/main'], function(main) { require(['jquery/nyt', 'underscore/nyt', 'foundation/models/user-data', 'foundation/tracking/tracking-mixin', 'foundation/views/page-manager', 'foundation/hosts'], function ($, _, userData, trackingMixin, pageManager, hosts) { var signupPromo = { taglines: { 'promo1': 'Journalism that matters.
More essential than ever.', 'promo2': 'Independent journalism.
More essential than ever.', 'promo3': 'Real reporting. Real news.', 'promo4': 'Independent. Trusted. Real.', 'promo5': 'Real journalism. Like nowhere else.', 'promo6': 'Truth is hard to find.
But easier with 1,000+ journalists looking.' }, /** * Initialization called when instantiating the view * @method initialize */ initialize: function () { this.$el = $('#signup-favor'); $(document).on('click', "#g-graphic.sub-promo-click", function(e){ if (e) { e.preventDefault(); } signupPromo.handleClick(); }); this.version = 'promo1'; userData.ready(function() { signupPromo.handleUserReady(); }); this.link = 'https://www.nytimes.com/DesktopHome'; }, trackImpression: function() { setTimeout(function() { signupPromo.tracking.trackingTriggerRaw( signupPromo.version, { module: 'election-sub-desktop-home', action: 'impression' }, 'impression' ); }, 1000); }, handleUserReady: function () { var view = this; console.log("abra "+ window.NYTD.Abra('www-signup-favor-test-v4')); if (window.NYTD.Abra('www-signup-favor-test-v4') == 'control') { return; } if (userData) { if (!userData.isHomeDeliverySubscriber() && !userData.isWebSubscriber() && !userData.isMobileSubscriber() && !userData.isTabletSubscriber()) { if (!$('html').hasClass('geo-country-US')) { this.link = 'https://www.nytimes.com/DesktopHomeINYT'; this.$el.find(".subscribe-link").attr("href", "http://www.nytimes.com/DesktopHomeINYT") } this.switchText(); } else { this.$el.find('.tagline').html('Support the mission of The Times.'); this.$el.find('.subscribe').html('Sponsor a student subscription today.'); this.version = 'studentSponsor'; this.link = 'https://www.nytimes.com/NativeSponsor'; this.$el.find('.subscribe-link').attr('href', 'https://www.nytimes.com/NativeSponsor'); } // if user is not already subscribed, show the element this.$el.removeClass('hidden'); this.trackImpression(); if (this.$el.closest('.column').hasClass('ab-column')){ this.$el.addClass('top-border'); } else if (this.$el.closest('.column').hasClass('b-column')) { this.$el.addClass('top-border').addClass('bottom-border'); } } }, switchText: function () { var hasAbra = false; hasAbra = window.NYTD && window.NYTD.Abra && window.NYTD.Abra('www-signup-favor-test-v4'); // check if this is part of an AB test if (hasAbra) { switch (window.NYTD.Abra('www-signup-favor-test-v4')) { case '1': this.$el.find('.tagline').html(this.taglines['promo1']); this.version = 'promo1'; break; case '2': this.$el.find('.tagline').html(this.taglines['promo2']); this.version = 'promo2'; break; case '3': this.$el.find('.tagline').html(this.taglines['promo3']); this.version = 'promo3'; break; case '4': this.$el.find('.tagline').html(this.taglines['promo4']); this.version = 'promo4'; break; case '5': this.$el.find('.tagline').html(this.taglines['promo5']); this.version = 'promo5'; break; case '6': this.$el.find('.tagline').html(this.taglines['promo6']); this.version = 'promo6'; break; } } }, handleClick: function (e) { if (e) { e.preventDefault(); } this.tracking.trackingTriggerRaw( this.version, { module: 'election-sub-desktop-home', action: 'click', eventName: 'sign-up' }, 'interaction' ); setTimeout(function() { window.location.href = signupPromo.link; }, 300); }, }; signupPromo.tracking = trackingMixin; signupPromo.pageManager = pageManager; signupPromo.hosts = hosts; signupPromo.initialize(); }); }); ``` -------------------------------- ### Require Foundation and Build Script Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Requires the main foundation script and then the build script for the 'tips-hp' module. This ensures all dependencies are loaded before execution. ```javascript require(['foundation/main'], function() { require(['https://static01.nyt.com/newsgraphics/2016/10/31/tips-hp/00b5b741a6c5682e24f945c547f78fbe98f2c27f/build.js']); // generated from src/script.js }); ``` -------------------------------- ### Basic HTML5-PHP Usage Source: https://github.com/masterminds/html5-php/blob/master/README.md Demonstrates how to use the high-level HTML5 library API to parse an HTML string and render it as HTML5. Assumes Composer autoloading is set up. ```php TEST

Hello World

This is a test of the HTML5 parser.

HERE; // Parse the document. $dom is a DOMDocument. $html5 = new HTML5(); $dom = $html5->loadHTML($html); // Render it as HTML5: print $html5->saveHTML($dom); // Or save it to a file: $html5->save($dom, 'out.html'); ``` -------------------------------- ### HTML5-PHP with Options Source: https://github.com/masterminds/html5-php/blob/master/README.md Shows how to pass configuration options to the HTML5 constructor for customizing parsing and serialization behavior. The $html variable should be defined prior to this snippet. ```php // An associative array of options $options = array( 'option_name' => 'option_value', ); // Provide the options to the constructor $html5 = new HTML5($options); $dom = $html5->loadHTML($html); ``` -------------------------------- ### JavaScript Function to Get Flex Data Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This JavaScript function retrieves data in JSON format, likely for dynamic content loading. It's used within a larger framework that manages flexible content types. ```javascript function getFlexData() { return {"data":{"item":[{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/09\/01\/science\/01WATER1\/01WATER1-videoSixteenByNine310.jpg","type":"article","headline":"A Sea of Hazards in Floodwaters","link":"https:\/\/www.nytimes.com\/2017\/08\/31\/us\/houston-contaminated-floodwaters.html"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/insider\/mattress-mack\/mattress-mack-videoSixteenByNine310.jpg","type":"video","headline":"A Mattress Store Turned Shelter","link":"https:\/\/www.nytimes.com\/video\/us\/100000005398367\/houston-harvey-mattress-shelter.html"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/us\/stormpics74\/stormpics74-videoSixteenByNine310.jpg","type":"slideshow","headline":"Harvey in Pictures","link":"https:\/\/www.nytimes.com\/2017\/08\/27\/us\/harvey-pictures-hurricane-storm.html?mcubz=0&\_r=0"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/dining\/360-tamircover\/360-tamircover-videoSixteenByNine310.jpg","type":"video","headline":"The Daily 360: Submerged Streets ","link":"https:\/\/www.nytimes.com\/video\/us\/100000005399523\/harvey-houston-flooding-rescue.html"}]}}; } ``` -------------------------------- ### Instantiate HTML5 Parser Source: https://github.com/masterminds/html5-php/wiki/Basic-Usage Create a new HTML5 parser instance. Options can be passed to the constructor to configure the parser's behavior. ```php // composer autoload require "vendor/autoload.php"; use Masterminds\HTML5; $html5 = new HTML5($options); ``` -------------------------------- ### Initialize Email Subscriber Widget (JavaScript) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Sets up an email subscriber widget using RequireJS. Configure the container, product code, and text for different user states. The widget includes event listeners for input focus and changes. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'morning-briefing-widget', productCode: 'NN', /* elementToHideOnSubscribe: '.nythp-morning-briefing-email-promo', */ text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get the Morning Briefing by email.', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get the Morning Briefing by email.'} }); setTimeout(function(){ var widget = document.getElementById('morning-briefing-widget'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Initialize Watching Module with Options Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This JavaScript code initializes the 'Watching' module from the Portal application. It configures options such as environment, matching heights for layout elements, and specific variations for scrolling behavior. Use this when setting up the main watching interface on a page. ```javascript require(['foundation/main'], function() { require(['homepage/main', 'https://int.nyt.com/apps/portals/assets/portal/app-31573ba689b023d9e52c26c6d6aa32ab.js'], function() { require(['portal/app'], function(Portal) { var opts = { env: 'production_published', matchHeight: { match: '.span-ab-layout.layout > .ab-column', container: '.c-column.column', maxHeight: 2000 } }; if (window.location.search.indexOf('portal_variant=watchingNoScroll') !== -1) { opts.variation = 'simple'; opts.poll = false; opts.limit = 20; } var watching = Portal.create('#nytint-hp-watching', opts); }); }); }); ``` -------------------------------- ### Require Main and Build Script - JavaScript Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Loads the main foundation script and then the generated build script. This is a common pattern for initializing complex JavaScript applications or graphics. ```javascript require(['foundation/main'], function() { require(['https://static01.nyt.com/newsgraphics/2017/08/30/houston-rescues/3217ab7ea858a2c388ceacbca5f753f34faf5343/build.js']); // generated from src/script.js }); ``` -------------------------------- ### Update HTML5 Class Usage (PHP) Source: https://github.com/masterminds/html5-php/blob/master/UPGRADING.md Illustrates the change in how to instantiate and use the HTML5 class. Version 2.x requires using the Masterminds namespace and instantiating the class, unlike the static method calls in 1.x. ```php $dom = \HTML5::loadHTML('....'); \HTML5::saveHTML($dom); ``` ```php use Masterminds\HTML5; $html5 = new HTML5(); $dom = $html5->loadHTML('....'); echo $html5->saveHTML($dom); ``` -------------------------------- ### Define Asset Path for Tips HP Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Defines the path for assets related to the 'tips-hp' module. This is used for loading specific resources. ```javascript define('__nytg/2016-10-31-tips-hp/assets', function() { return 'https://static01.nyt.com/newsgraphics/2016/10/31/tips-hp/00b5b741a6c5682e24f945c547f78fbe98f2c27f/'; }); ``` -------------------------------- ### Tooltip Styling - CSS Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Provides CSS for styling tooltips, including positioning, appearance, and transitions. It also includes a media query for responsive adjustments on smaller screens. ```css .tooltip { position: absolute; bottom: 50px; left: 50%; margin-left: -150px; padding: 10px 15px; background: #fff; border-radius: 3px; font-size: 13px; line-height: 1.4; color: #000; box-shadow: 0 1px 2px rgba(0,0,0,.33); z-index: 1000; transition: all .3s; transition-delay: .1s; } .tooltip-hidden { opacity: 0; transition: all .3s; transition-delay: .1s; } @media (max-width: 590px) { div.tooltip { bottom: -1px; width: calc(100%); left: -1px !important; right: -1px !important; top: auto !important; width: auto !important; } } ``` -------------------------------- ### Configure Entity Encoding (Constructor) Source: https://github.com/masterminds/html5-php/wiki/Basic-Usage Instantiate the HTML5 parser with the 'encode_entities' option set to TRUE to ensure all HTML5 entities are encoded by default. ```php $html5 = new HTML5(array('encode_entities' => TRUE)); ``` -------------------------------- ### CSS Styling for Audio Brief Component Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Styles the '.audio-brief' component, including image dimensions, float, summary padding, and audio player margins. It also customizes the appearance of the art19-web-player and daily subscription links. ```css .audio-brief .image { width: 75px; height: 75px; float: right; clear: right; margin: 4px 0 6px 12px; } .audio-brief .summary { padding-bottom: 10px; } .audio-brief .audio { margin: 0; } .audio-brief .art19-web-player { margin-bottom: 0; } .audio-brief .art19-web-player.awp-micro .awp-left { border-right: none; } .audio-brief .art19-web-player.awp-micro .awp-brand-logo { padding: 0; } .audio-brief .awp-brand-logo img { display: none; } .audio-brief .awp-embed-button{ cursor: pointer; } #daily-sub-links{ width:100%; padding:0; margin:-10px 0 0 0; } #daily-sub-links p{ font-family:"nyt-franklin",arial,helvetica,sans-serif; font-weight:400; font-size: 12px; line-height: 15px; color:#000; } #daily-sub-links p a{ display:inline-block; color: #326891; padding-right: 8px; padding-left: 6px; border-right:1px solid #ccc; } #daily-sub-links p a:last-child{ border-right:none; } ``` -------------------------------- ### Define Big Assets Path for Tips HP Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Defines the path for larger assets related to the 'tips-hp' module. This is typically used for high-resolution images or media. ```javascript define('__nytg/2016-10-31-tips-hp/big-assets', function() { return 'https://static01.nyt.com/newsgraphics/2016/10/31/tips-hp/assets/'; }); ``` -------------------------------- ### JavaScript Asset and Build Configuration Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This JavaScript code sets global variables for asset paths and then uses a `require` call to load a specific build script from a CDN. This is typical for managing external dependencies and initializing application logic. ```javascript var NYTG_ASSETS = "_assets/"; var NYTG_BIG_ASSETS = "_big_assets/"; require(['foundation/main'], function() { require(["https://static01.nyt.com/newsgraphics/2015/hp-thumbstrip/assets/build.js"]); }); ``` -------------------------------- ### Configure Email Subscriber Widget (JavaScript) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Sets up an email subscriber widget using the 'nytint/email-subscriber' module. Configure container ID, product code, and text for different states. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'morning-briefing-widget-eu', productCode: 'MBE', /* elementToHideOnSubscribe: '.nythp-morning-briefing-email-promo', */ text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get the Morning Briefing by email.', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get the Morning Briefing by email.'} }); setTimeout(function(){ var widget = document.getElementById('morning-briefing-widget-eu'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Initialize Google Analytics Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Initializes the Google Analytics object. This should be called early in your application's lifecycle. ```javascript var _gaq = _gaq || []; ``` -------------------------------- ### Fetch and Render Smarter Living Articles (JavaScript) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This JavaScript code fetches 'Smarter Living' articles from a NYT API and dynamically updates the DOM. It uses Underscore.js and jQuery for templating and AJAX requests. Ensure the 'foundation/main' module is required. ```javascript require(['foundation/main'], function (main) { require(['underscore/nyt', 'jquery/nyt', 'foundation/views/base-view'], function (_, $, BaseView) { var SmarterLiving = BaseView.extend({ template: _.template('

' + '<%= headline %>

' + '
'), events: { 'click article a': 'handleArticleLinkClick' }, articles: [], initialize: function () { const view = this; if (!this.pageManager.flag('smarterLivingRec')) { return; } this.$el = $('.nythpSmarterLiving'); this.setupImpressionTracking = _.once(this._setupImpressionTracking); $.ajax({ url: 'https://rec.api.nytimes.com/svc/recommendations/v4/smarter_living.json', xhrFields: { withCredentials: true } }) .done(function (data) { view.setupImpressionTracking(); _.each(data.assets, function (item) { view.articles.push(item.url); }); // iterate over the existing articles view.$el.find('article').each(function (index) { // replace with articles from rec service $(this).replaceWith(view.template(data.assets[index])); }); }) .always(function () { // unhide articles view.$el.css('display', 'block'); }); }, _setupImpressionTracking: function () { if (this.pageManager.isComponentVisible(this.$el)) { this.recordTrackingImpression(); } else { this.subscribe('nyt:page-scroll', this.handleScroll); } }, handleArticleLinkClick: function (ev) { const view = this; const $el = $(ev.currentTarget); var href = this.trackingAppendParams($el.attr('href'), { 'action': 'click', 'pgtype': 'Homepage', 'clickSource': 'story-heading', 'module': 'smarter-living', 'region': 'second-column-region', 'contentCollection': 'smarter-living', 'mData': $.param({ articles: view.articles }) }); $el.attr('href', href); }, handleScroll: function () { if (this.pageManager.isComponentVisible(this.$el)) { this.recordTrackingImpression(); this.stopSubscribing('nyt:page-scroll'); } }, recordTrackingImpression: function () { const view = this; this.trackingTriggerImpression('Impression', { 'module': 'smarter-living', 'pgtype': 'Homepage', 'region': 'second-column-region', 'action': 'impression', 'proxyEventType': 'impression', 'timestamp': new Date().getTime(), 'mData': { articles: view.articles } }); } }); new SmarterLiving(); }); }); ``` -------------------------------- ### Configure XML Namespaces in HTML5 Parser Source: https://github.com/masterminds/html5-php/blob/master/README.md To enable XML style namespaces, configure the main HTML5 instance with the 'xmlNamespaces' option set to true. This allows for parsing documents with XML namespaces. ```php use Masterminds\HTML5; $html = new HTML5(array( "xmlNamespaces" => true )); $dom = $html->loadHTML(''); $dom->documentElement->namespaceURI; // http://www.example.com ``` -------------------------------- ### Serialize DOM to File Source: https://github.com/masterminds/html5-php/wiki/Basic-Usage Save a DOMDocument, DOMDocumentFragment, or DOMNodeList object to a specified file path. ```php // $dom is either a DOMDocument, DOMDocumentFragment, or DOMNodeList. $string = $html5->save($dom, 'path/to/file.html'); ``` -------------------------------- ### Custom InstructionProcessor Interface Implementation Source: https://github.com/masterminds/html5-php/wiki/Processor-Instructions Defines a custom instruction processor that increments a counter for each processed instruction. The `process` method returns the element to be attached to the DOM. ```php bar++; return $element; } } ``` -------------------------------- ### JavaScript Data Fetching Configuration Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Defines a JavaScript function to retrieve configuration data for a slideshow. This data includes options for dimensions, JSONP endpoint, and a link to the article. ```javascript function getFlexData() { return {"data":{"options":{"width":375,"height":380,"jsonp":"https:\/\/static01.nyt.com\/slideshow\/2017\/08\/28\/world\/europe\/tk.slideshow.jsonp","link":"https:\/\/www.nytimes.com\/2017\/08\/30\/world\/europe\/princess-diana-death-anniversary.html"},"photos":{"photo":{"url":"","credit":""}},"advanced":{"delay":3,"limitjsonp":0,"rendition":"largeHorizontal375","targetoverride":"","abbreviatecredits":false}}}; } ``` -------------------------------- ### Custom Parser with Instruction Processor Source: https://github.com/masterminds/html5-php/wiki/Processor-Instructions A custom parsing function that creates an instruction processor instance and attaches it to the DOM tree builder before parsing. ```php function my_parser(\HTML5\Parser\InputStream $input) { // Create an instance of the processing instruction. $foo = new foo(); $events = new DOMTreeBuilder(); // Attach it to the event based DOM tree builder. $events->setInstructionProcessor($foo); $scanner = new Scanner($input); $parser = new Tokenizer($scanner, $events); $parser->parse(); return $events->document(); } ``` -------------------------------- ### Initialize Analytics and Page Manager Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This JavaScript code initializes analytics and page management functionalities. It conditionally loads the tagx-simple.min.js analytics script only if 'disable_tagx' is not present in the URL. The script is executed after the DOM is ready. ```javascript require(['foundation/main'], function () { require(['homepage/main']); require(['jquery/nyt', 'foundation/views/page-manager'], function ($, pageManager) { if (window.location.search.indexOf('disable_tagx') > 0) { return; } $(document).ready(function () { require(['https://a1.nyt.com/analytics/tagx-simple.min.js'], function () { pageManager.trackingFireEventQueue(); }); }); }); }); ``` -------------------------------- ### Define Big Assets Path - JavaScript Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Defines the base URL for larger assets. This is similar to the 'assets' definition but may point to a different directory or CDN for heavier resources. ```javascript define('\_nytg/2017-08-30-houston-rescues/big-assets', function() { return 'https://static01.nyt.com/newsgraphics/2017/08/30/houston-rescues/assets/'; }); ``` -------------------------------- ### Define Asset Path - JavaScript Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Defines the base URL for static assets. This is typically used for loading images or other resources associated with the graphic. ```javascript define('\_nytg/2017-08-30-houston-rescues/assets', function() { return 'https://static01.nyt.com/newsgraphics/2017/08/30/houston-rescues/3217ab7ea858a2c388ceacbca5f753f34faf5343/'; }); ``` -------------------------------- ### Description Box Styling - CSS Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Styles a description box, including its appearance, positioning, and a pseudo-element for creating a pointer or arrow. Includes a variant for left-aligned pointers. ```css .description { margin-left: 10px; font-size: 15px; line-height: 15px; max-width: 150px; padding: 8px 12px; color: #000; border-radius: 3px; background: #ffffff; box-shadow: 0px 1px 2px rgba(0, 0, 0, 0.33); } .description:after { content: ''; position: absolute; left: 0; top: 50%; width: 0; height: 0; border: 5px solid transparent; border-right-color: #ffffff; border-left: 0; margin-top: -5px; margin-left: -5px; } .description.lefty:after { position: absolute; left: auto; right: 0; top: 50%; width: 0; height: 0; border: 5px solid transparent; border-left-color: #ffffff; box-shadow: none; border-right: 0; margin-top: -5px; margin-right: -5px; } ``` -------------------------------- ### NYTD Flex Types Initialization Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html This code initializes a JavaScript array `NYTD.FlexTypes` and pushes a configuration object into it. This is likely used to register custom content types or components within the NYTD framework. ```javascript var NYTD=NYTD || {}; NYTD.FlexTypes = NYTD.FlexTypes || []; NYTD.FlexTypes.push({"target":"FT100000005396835","type":"HP Thumbstrip","data":{"item":[{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/09\/01\/science\/01WATER1\/01WATER1-videoSixteenByNine310.jpg","type":"article","headline":"A Sea of Hazards in Floodwaters","link":"https:\/\/www.nytimes.com\/2017\/08\/31\/us\/houston-contaminated-floodwaters.html"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/insider\/mattress-mack\/mattress-mack-videoSixteenByNine310.jpg","type":"video","headline":"A Mattress Store Turned Shelter","link":"https:\/\/www.nytimes.com\/video\/us\/100000005398367\/houston-harvey-mattress-shelter.html"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/us\/stormpics74\/stormpics74-videoSixteenByNine310.jpg","type":"slideshow","headline":"Harvey in Pictures","link":"https:\/\/www.nytimes.com\/2017\/08\/27\/us\/harvey-pictures-hurricane-storm.html?mcubz=0&\_r=0"},{"thumb":"https:\/\/static01.nyt.com\/images\/2017\/08\/31\/dining\/360-tamircover\/360-tamircover-videoSixteenByNine310.jpg","type":"video","headline":"The Daily 360: Submerged Streets ","link":"https:\/\/www.nytimes.com\/video\/us\/100000005399523\/harvey-houston-flooding-rescue.html"}]}}); ``` -------------------------------- ### Artboard and Text Styling - CSS Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Styles the main artboard container and its paragraphs, defining font properties, line height, and text alignment. Includes specific paragraph styles for different text elements. ```css #g-harvey\_hp-Artboard\_2-box { max-width:600px; } #g-harvey\_hp-Artboard\_2-box .g-artboard { margin:0 auto; } #g-harvey\_hp-Artboard\_2-box .g-artboard p { margin:0; } .g-aiAbs { position:absolute; } .g-aiImg { display:block; width:100% !important; } .g-aiPointText p { white-space: nowrap; } ``` -------------------------------- ### Parse HTML5 File Source: https://github.com/masterminds/html5-php/wiki/Basic-Usage Load an HTML5 file or resource directly into a DOMDocument object without needing to load it into a string first. ```php // Parse the document. $dom is a DOMDocument. $dom = $html5->loadHTMLFile('path/to/file.html'); ``` -------------------------------- ### Configure Implicit XML Namespaces in HTML5 Parser Source: https://github.com/masterminds/html5-php/blob/master/README.md You can also define default prefixes for namespaces that do not require explicit namespace declarations in the HTML. Elements using these prefixes will be automatically namespaced. ```php use Masterminds\HTML5; $html = new HTML5(array( "implicitNamespaces"=>array( "t"=>"http://www.example.com" ) )); $dom = $html->loadHTML(''); $dom->documentElement->namespaceURI; // http://www.example.com ``` -------------------------------- ### Configure California Today Email Widget (JavaScript) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Initializes the 'nytint/email-subscriber' for the 'California Today' newsletter. It configures specific IDs and text content for the widget. ```javascript require.config({ paths: { 'nytint/email-subscriber' : 'https://int.nyt.com/applications/email-subscriber/client' } }); require(['foundation/main'], function() { require(['nytint/email-subscriber'], function(Subscriber) { Subscriber.setup({ containerId: 'california-today-widget', productCode: 'CA', /* elementToHideOnSubscribe: '.nythp-morning-briefing-email-promo', */ text: {unregisteredButton: 'Sign Up', unregisteredPlaceholder: 'Get California Today by email.', registeredButton: 'Sign Up', alreadySubscribedMessage: 'You’re already subscribed.', thanksMessage: 'You’ve signed up as %email%', emailPreferencesLinkText: 'Update your mail preferences »', errorMessage: 'Error submitting, please try again.', registeredWelcome: 'Get California Today by email.'} }); setTimeout(function(){ var widget = document.getElementById('california-today-widget'); var container = widget.getElementsByTagName('div')[0]; var form = widget.getElementsByTagName('form')[0]; var status = container.getAttribute('data-status'); var notify = widget.getElementsByClassName('notify-email')[0]; if(notify !== undefined){ var origtext = notify.getAttribute('placeholder'); var newtext = 'Please enter your email address'; var button = container.getElementsByTagName('button')[0]; widget.setAttribute('class','clearfix'); notify.addEventListener('mouseover',function(){ notify.setAttribute('placeholder',newtext); }); notify.addEventListener('mouseout',function(){ notify.setAttribute('placeholder',origtext); }); notify.addEventListener('focus',function(){ notify.setAttribute('placeholder',''); }); } if(form !== undefined){ notify.addEventListener('keyup',function(){ form.setAttribute('class','dirtyform'); }); container.setAttribute('class','not-signedin'); } else { container.setAttribute('class','signedin'); } },2000); }); }); ``` -------------------------------- ### Serialize DOM to HTML String Source: https://github.com/masterminds/html5-php/wiki/Basic-Usage Convert a DOMDocument, DOMDocumentFragment, or DOMNodeList object into an HTML string. ```php // $dom is either a DOMDocument, DOMDocumentFragment, or DOMNodeList. $string = $html5->saveHTML($dom); ``` -------------------------------- ### Dynamic Content Appending with jQuery (JavaScript) Source: https://github.com/masterminds/html5-php/blob/master/test/benchmark/example.html Uses jQuery and Underscore.js to dynamically append content from an Australian region to the main content area. It also inserts a specific section heading for Australian content. ```javascript require(['foundation/main'], function() { require(['jquery/nyt', 'underscore/nyt'], function($, _) { $("#span-ab-bottom-region div.split-3-layout").append($("#span-ab-bottom-au-region div.split-3-layout > div.column").addClass("column-au-region").remove()); $("#span-ab-bottom-region div.split-3-layout").prepend($('

Australia Picks

')); var auHeight = egional.max($("#span-ab-bottom-region div.split-3-layout .column.column-au-region article").map(function(i, el) { return $(el).height(); })); $("#span-ab-bottom-region div.split-3-layout .column.column-au-region").css({"min-height": (auHeight+6)+"px"}); }) }) ```