Viral Dubai chocolate bar partially unwrapped on gold foil with oozing green pistachio knafeh filling

Viral Dubai Chocolate Bar Recipe: 5 Easy Steps to Crispy Crunch

Few desserts in the modern culinary era have captivated social media, home bakers, and luxury food enthusiasts quite like the Viral Dubai Chocolate Bar Recipe. Originally born in the glamorous sweet boutiques of Dubai, specifically crafted by the visionary chocolatiers at FIX Dessert Chocolatier under the legendary name “Can’t Get Knafeh of It”, this confectionery masterpiece has taken TikTok, Instagram, and Pinterest by absolute storm. Breaking one of these heavyweight chocolate bars open unleashes an unforgettable sensory explosion: the crisp, clean snap of high-gloss tempered chocolate yielding to an intensely vibrant emerald-green center brimming with velvety pistachio cream and shatteringly crisp, butter-toasted kataifi pastry strands.

While acquiring an authentic imported bar can cost upwards of $20 to $50, with long waitlists and fragile shipping conditions, making this viral sensation in your own kitchen is shockingly simple, remarkably affordable, and undeniably superior in both freshness and flavor. In this comprehensive, chef-crafted guide, you will master every single stage of making the ultimate Viral Dubai Chocolate Bar from scratch, including how to achieve an ultra-crispy knafeh crunch, how to temper chocolate for a mirror-like shine, and how to balance luscious pistachio cream with a whisper of nutty tahini.

Viral Dubai Chocolate Bar cross section showing creamy pistachio knafeh filling and glossy dark chocolate shell
The iconic cross-section of our homemade viral Dubai chocolate bar, loaded with golden toasted kataifi and velvety pistachio cream.

What is the Viral Dubai Chocolate Bar and Why is it Famous?

The viral Dubai chocolate bar is a modern Middle Eastern confectionery fusion that reimagines the centuries-old traditional dessert known as Knafeh (or Kunafa) inside a luxury European-style chocolate shell. Traditional knafeh is celebrated throughout the Levant for its combination of spun, finely shredded phyllo pastry dough (called kataifi), soaked in fragrant sweet sugar syrup, and layered with melted cheese or rich clotted cream (ashta).

In this viral adaptation, the shredded pastry is gently cut into delicate pieces, meticulously toasted in pure unsalted butter until it reaches a deep, radiant golden hue, and then folded into rich, creamy pistachio cream balanced with a hint of roasted sesame tahini. The entire mixture is then generously encased in thick, premium tempered chocolate. The contrast between the cool, snappy chocolate shell and the warm, nutty, ultra-crispy, creamy interior creates a mouthfeel that is completely unmatched by conventional candy bars.

Why You Will Fall in Love with This Homemade Copycat Recipe

If you have ever stared at viral videos wondering whether this treat lives up to the monumental social media hype, the short answer is an enthusiastic yes. Here is why you will fall in love with making this recipe at home:

  • Shatteringly Crisp Texture: The secret lies in toasting the kataifi pastry in real dairy butter, creating thousands of microscopic crispy air pockets that remain extraordinarily crunchy even after days of storage.
  • Pure Gourmet Ingredients: You have full control over the quality. No artificial green dyes, no hydrogenated palm oils, and no corn syrup fillers. Just pure pistachios, real cocoa butter, and authentic pastry.
  • Fraction of the Price: Buying a single imported bar online can cost over $35 plus exorbitant express dry-ice shipping fees. Making two gigantic bars at home costs less than $12 total in raw ingredients.
  • Effortless Customization: Prefer a darker, less sweet bite? Use 70% bittersweet chocolate. Want a fun color swirl? Paint the molds with edible green cocoa butter or golden luster dust before pouring.
  • Foolproof in 25 Minutes: Aside from chilling time in the refrigerator, the active hands-on preparation takes less than half an hour from start to finish.

Homemade Copycat vs Original FIX Store-Bought Dubai Chocolate Bar

Feature Homemade Copycat Dubai Bar Store-Bought / Imported Original
Average Cost $5.50 – $6.50 per large bar $25.00 – $45.00 plus shipping
Kataifi Crunch Factor 10/10 (Freshly toasted butter crunch) 7/10 (Can soften during transit)
Customization Level Fully customizable (Dark, Milk, White) Fixed formula and sweetness
Preparation Time 25 minutes hands-on Weeks waiting for restocks
Preservatives & Additives Zero artificial additives May contain stabilizing shelf-life agents

Key Ingredients for Authentic Taste and Unmatched Crunch

To recreate the authentic flavor profile that catapulted this treat to global fame, selecting the proper ingredients is paramount. Fortunately, you only need four primary staples, plus a few optional flavor enhancers:

Viral Dubai Chocolate Bar filling with golden toasted kataifi pastry threads and rich pistachio cream in skillet
Toasting the shredded kataifi in melted butter until deeply golden and shatteringly crisp.
  1. High-Quality Chocolate (280g / 10 oz): Do not use standard baking chips that contain stabilizers like soy lecithin, which prevent a clean melt. Choose high-end chocolate bars or couverture callets with real cocoa butter (such as Lindt, Guittard, or Callebaut). A 50/50 blend of 60% dark chocolate and creamy milk chocolate yields the absolute best harmony between sweetness and deep cocoa depth.
  2. Kataifi Pastry (150g / 5.3 oz): Kataifi is finely shredded phyllo dough that looks like spun vermicelli angel hair. You can find it in the frozen dessert aisle of Middle Eastern, Greek, Mediterranean, or international grocers. Ensure you thaw it overnight in the refrigerator before using.
  3. Pure Pistachio Cream or Pistachio Paste (180g / 3/4 cup): This is the lush emerald heart of the bar. Look for Italian pistachio spread (crema di pistacchio) or 100% ground pistachio paste. Italian varieties often have a touch of white chocolate or milk powder, providing an irresistibly creamy consistency.
  4. Unsalted European Butter (35g / 2.5 tbsp): High-fat butter (at least 82% butterfat) is essential for toasting the pastry dough evenly without excessive water evaporation, creating that characteristic golden richness.
  5. Runny Tahini Paste (25g / 1.5 tbsp): The secret weapon used by Middle Eastern pastry chefs. A small splash of pure sesame tahini adds a subtle earthy complexity that tempers the sweetness of the pistachio cream, preventing the filling from tasting cloying.
  6. Flaky Sea Salt: A generous pinch of Maldon sea salt balances the rich chocolate and elevates the nutty undertones to gourmet heights.

Essential Kitchen Equipment for Success

You do not need an industrial pastry kitchen to make viral Dubai chocolate bars, but having a few specific tools will guarantee bakery-quality results:

  • Deep Silicone Chocolate Bar Molds: The signature Dubai chocolate bar is exceptionally thick (roughly 1 inch / 2.5 cm deep) to hold a massive layer of knafeh filling. Silicone molds allow you to effortlessly pop the set bars out without cracking the chocolate shell.
  • Wide Non-Stick Skillet: A large 10-inch or 12-inch pan allows the shredded pastry to spread out in an even layer so every single strand browns uniformly without steaming.
  • Small Offset Spatula: Indispensable for spreading the melted chocolate cleanly up the walls of the mold and smoothing the pistachio knafeh filling.
  • Pastry Brush: Helps you paint an even, seamless chocolate layer into the corners of your mold.
  • Heat-Proof Glass Bowl: For melting your chocolate gently over a water bath.

Step-by-Step Instructions with Chef Secrets

Follow these meticulously tested steps to achieve a flawless chocolate snap and that viral, oozy, crunchy green interior:

Phase 1: Thawing and Chopping the Kataifi Pastry

Take your thawed kataifi pastry out of the package. It will look like a long bundle of fine wheat threads. Using a sharp chef knife on a large cutting board, finely chop the pastry into small pieces approximately 1/4 inch to 1/2 inch (0.5 to 1 cm) long. Do not leave the strands too long, otherwise they will be difficult to fold neatly into the chocolate molds.

Phase 2: Browning the Pastry to Golden Perfection

Place your wide skillet over medium-low heat and melt 35g of unsalted European butter. Once the butter is melted and begins to gently bubble, add all of your chopped kataifi pastry. Use a heat-safe spatula or wooden spoon to continuously toss and turn the pastry shreds.

Take your time with this step. The pastry will initially absorb the butter and look pale, but after approximately 7 to 10 minutes of patient stirring, it will transform into a radiant, uniform golden-brown hue and release a rich, nutty, toasted aroma. As soon as it reaches this golden color, immediately transfer the toasted kataifi out of the hot skillet into a cool mixing bowl. Leaving it in the hot pan will cause the delicate pastry to burn from residual heat.

Phase 3: Crafting the Pistachio Knafeh Filling

Allow the toasted pastry to cool down for 5 to 7 minutes until it is warm to the touch rather than piping hot. If the pastry is too hot, it can break down the emulsification of the pistachio cream. Once cooled, pour 180g of smooth pistachio cream, 25g of runny tahini, and a generous pinch of flaky sea salt directly over the toasted kataifi. Fold gently using your spatula until every single golden thread is coated in luxurious green pistachio butter. Set the bowl aside at room temperature.

Phase 4: Tempering and Painting the Chocolate Shell

To achieve a professional chocolate bar that does not melt immediately in your fingers and snaps loudly when broken, gentle tempering is key. Roughly chop your 280g of chocolate. Place two-thirds (roughly 190g) of the chocolate into a heat-safe glass bowl set over a small saucepan of gently simmering water (bain-marie), making sure the bottom of the bowl does not touch the water.

Stir gently with a dry spatula until the chocolate is completely melted, glossy, and reaches approximately 115°F (46°C). Remove the bowl from the heat, wipe the bottom completely dry (a single drop of water can seize the chocolate), and stir in the remaining one-third (90g) of unmelted chocolate. Stir continuously until all the added chocolate has melted smoothly and the temperature drops to about 88°F to 90°F (31°C to 32°C).

Spoon roughly 2 to 3 tablespoons of tempered chocolate into each cavity of your silicone mold. Use a pastry brush or the back of a small spoon to paint the chocolate up the sides of each cavity, ensuring there are no thin spots or holes. Place the mold into the freezer for 8 to 10 minutes until the chocolate shell is firm to the touch.

Phase 5: Filling, Capping, and Final Chill

Remove the chocolate-lined mold from the freezer. Spoon generous mounds of the pistachio knafeh filling into each chocolate cavity, packing it down gently and smoothing the top with your offset spatula. Make sure to leave a 2mm gap at the top edge of the mold so the bottom chocolate cap can seal the filling completely.

Pour the remaining melted tempered chocolate evenly over the filling. Smooth the surface using a bench scraper or spatula so the bottom of the bar is completely flat and level. Gently tap the silicone mold against your countertop several times to release any trapped air bubbles.

Transfer the mold to the refrigerator (not the freezer) for 25 to 30 minutes. Once the chocolate is completely firm, matte, and gently pulling away from the silicone edges, gently peel the silicone mold backwards. Your gorgeous, glossy, artisanal Dubai chocolate bars will slide out effortlessly!

Viral Dubai Chocolate Bar plated on dark luxury slate board with crushed pistachios
Artisanal homemade Dubai chocolate bars sliced and served with a cup of rich hot espresso.

Pro-Chef Tips for That Legendary “Chocolate Snap”

The hallmark of a world-class chocolate bar is its texture and clean auditory snap. Here are expert secrets straight from professional chocolatiers to ensure your creation turns out flawless:

  • Keep Water Away at All Costs: Water is the absolute mortal enemy of melted chocolate. Even microscopic droplets of steam or condensation from the refrigerator can cause your chocolate to seize into a dull, grainy, unworkable paste. Always dry your utensils thoroughly.
  • Do Not Over-Freeze: While a brief 8-minute freezer flash is great for setting the shell walls, avoid leaving the finished bars in the freezer for hours. Freezing chocolate causes condensation to form on the surface upon thawing, resulting in unsightly sugar bloom (white streaks).
  • Let the Kataifi Cool Before Mixing: If you fold boiling-hot toasted pastry into pistachio cream, the heat can cause the oils in the pistachio paste and tahini to separate, resulting in a greasy texture. Let the pastry cool to warm room temperature first.
  • Use Deep Silicone Molds: Shallow molds designed for standard candy bars will not hold enough pistachio knafeh to deliver that satisfying viral cross-section. Invest in molds with at least 0.8 inch to 1 inch depth.

Chocolate Shell Comparison Matrix

Chocolate Type Cocoa Percentage Sweetness Level Flavor Profile & Recommendation
Dark Chocolate 65% – 72% Low to Moderate Top Recommendation: The slight bitterness cuts through the rich pistachio cream beautifully, creating a balanced, luxurious palate.
Milk Chocolate 35% – 42% High Classic FIX Style: Rich, nostalgic, and creamy. Best when paired with extra flaky sea salt to temper the sugar content.
Semi-Sweet 50/50 Blend 50% – 55% Balanced Crowd Favorite: Combining equal parts 70% dark and 38% milk chocolate yields the absolute best texture and universal appeal.
White Chocolate 30% (Cocoa Butter) Very High Decadent and sweet. Excellent when infused with culinary matcha green tea powder for an all-green aesthetic.

Variations and Creative Flavor Twists

Once you have mastered the classic pistachio knafeh formula, experiment with these sensational, chef-tested flavor variations:

  • The Lotus Biscoff Crunch Bar: Replace half of the pistachio cream with melted Lotus Biscoff cookie spread. Fold in crushed speculoos cookies alongside the toasted kataifi for a warm spiced caramel profile.
  • Matcha White Chocolate Dubai Bar: Coat your mold with tempered white chocolate blended with 1 teaspoon of ceremonial grade matcha powder. Fill with matcha pistachio knafeh for a stunning, double-green Japanese fusion treat.
  • Dark Chocolate Orange Blossom: Add two drops of pure orange blossom water (or finely grated organic orange zest) into the pistachio knafeh filling. The fragrant citrus aroma cuts through the dark chocolate shell with sublime Mediterranean elegance.
  • Dubai Chocolate Hazelnut Nutella: Swap the pistachio paste for roasted Piedmont hazelnut praline paste and drizzle with melted dark chocolate for a homemade Rocher-style experience.

Serving Suggestions & Beverage Pairings

Because the Dubai chocolate bar is extraordinarily rich, a little goes a long way. Slice the bar into 1/2-inch thick fingers using a warm, dry chef knife (run your knife under hot water, dry thoroughly with a towel, and press straight down for razor-sharp edges).

For beverage pairings, pair this decadent treat with a bitter, roasted drink that balances the sweet richness of the pistachio center. Traditional cardamom-scented Arabic coffee (Qahwa), a double shot of Italian espresso, or a pot of unsweetened Moroccan mint green tea are absolute perfection. For an indulgent weekend dessert board, serve alongside our savory Crispy Feta Fried Eggs on Sourdough for a sensational sweet-and-savory brunch spread!

Common Mistakes to Avoid When Making Dubai Chocolate

Avoid these common pitfalls that home cooks frequently encounter when attempting this viral recipe:

  1. Under-Toasting the Kataifi: Pale, blond kataifi will taste doughy and quickly turn soft when mixed with pistachio cream. Keep toasting until it is deeply amber-golden and crackles loudly when pressed.
  2. Applying the Chocolate Shell Too Thin: If the walls of your chocolate shell are too thin, the bar will crack open under the pressure of packing the knafeh filling. Paint two thin coats or one generous coat along the corners.
  3. Using Pre-Ground Dry Pistachio Flour: Dry ground pistachios will not create a smooth, creamy center. You must use smooth, runny pistachio cream or butter.
  4. Demolding Too Early: If the chocolate is even slightly soft when you try to flex the silicone mold, the bar will bend, lose its glossy finish, and leave chocolate behind in the mold. Be patient and wait until it is fully set.

Storing Tips for the Recipe

To preserve that signature shatteringly crisp knafeh crunch for as long as possible, follow these storage rules:

  • Room Temperature: If your chocolate was properly tempered, you can store the finished bars in a sealed airtight container in a cool, dark pantry (between 65°F and 70°F / 18°C and 21°C) for up to 10 days. The crunch remains at its absolute peak at room temperature.
  • Refrigeration: In warm climates or during summer months, store the bars in the refrigerator wrapped tightly in parchment paper and placed in an airtight container for up to 3 weeks. Bring to room temperature for 10 minutes before slicing to prevent the chocolate shell from cracking irregularly.
  • Freezing: You can freeze fully assembled bars for up to 2 months. Wrap each bar in two layers of plastic wrap followed by aluminum foil. Thaw in the refrigerator overnight before enjoying.

Nutrition & Macro Breakdown

Nutrient Per Serving (1/4 Bar / approx. 65g) Daily Value (% DV)
Calories 395 kcal 20%
Total Fat 26g 33%
Saturated Fat 11g 55%
Cholesterol 12mg 4%
Sodium 85mg 4%
Total Carbohydrates 34g 12%
Dietary Fiber 4g 14%
Sugars 22g –
Protein 7g 14%

FAQs (Frequently Asked Questions)

Can I make this recipe without a silicone chocolate mold?

Yes! If you do not own a specialized chocolate bar mold, line a standard 8×4 inch metal loaf pan or square 8×8 inch baking dish with parchment paper. Pour your bottom chocolate layer, freeze until set, spread the pistachio knafeh filling evenly across the dish, and pour the top chocolate layer over it. Once set in the fridge, lift the parchment paper out and slice into thick dessert bars with a warm knife.

Where can I buy kataifi pastry?

Kataifi (shredded phyllo pastry) is widely available in the freezer section of Mediterranean, Greek, Turkish, and Middle Eastern specialty grocery stores. It is also available year-round online on Amazon and specialty culinary supply websites. If you cannot find kataifi anywhere, an acceptable emergency substitute is crushed toasted phyllo dough sheets or toasted shredded unsalted phyllo pastry.

Can I make my own pistachio cream from scratch?

Absolutely. Toast 200g of raw shelled pistachios in an oven at 325°F (160°C) for 8 minutes. Place the warm pistachios into a high-powered food processor or blender with 2 tablespoons of powdered sugar, 1 tablespoon of neutral oil (or melted cocoa butter), and a pinch of salt. Blend on high speed for 5 to 7 minutes until the nuts release their natural oils and transform into a luscious, satin-smooth butter.

Why did my chocolate bloom with white spots?

Chocolate bloom occurs when chocolate is subjected to drastic temperature fluctuations or when it cools too slowly without proper tempering, causing cocoa butter crystals to separate and migrate to the surface. It is entirely safe to eat, though it affects cosmetic appearance. To prevent this, temper your chocolate according to the instructions and avoid condensation.

Is this Dubai chocolate bar recipe gluten-free?

Traditional kataifi pastry is made from wheat flour and is therefore not gluten-free. However, you can make a 100% gluten-free version by using certified gluten-free kataifi (available from specialized bakeries) or substituting with toasted crushed gluten-free puffed rice crispies or gluten-free toasted shredded coconut threads.

Can I prepare this recipe ahead for holiday gifting?

Yes, this recipe makes an extraordinary luxury gift. Wrap each fully set bar in food-safe golden confectioner foil, slide it into a sleek kraft gift box tied with natural twine, and keep in a cool spot. It will stay wonderfully fresh and crispy for over a week at room temperature.

Conclusion

The Viral Dubai Chocolate Bar Recipe is more than just a passing internet trend; it is a timeless, sublime celebration of textures and flavors that every sweet lover deserves to experience. The marriage of shatteringly crispy toasted kataifi pastry, rich and earthy pistachio cream, and premium tempered chocolate creates a truly unforgettable confection. By following this foolproof copycat guide, you can skip the expensive international markups and enjoy bakery-quality luxury bars right from your kitchen.

Try this recipe today, snap that famous viral cross-section, and share your delicious creations! Don’t forget to rate this recipe 5 stars below and leave a comment with your favorite chocolate blend.

Print
clock clock iconcutlery cutlery iconflag flag iconfolder folder iconinstagram instagram iconpinterest pinterest iconfacebook facebook iconprint print iconsquares squares iconheart heart iconheart solid heart solid icon

Viral Dubai Pistachio Knafeh Chocolate Bar


  • Author: Felis
  • Total Time: 25 mins
  • Yield: 2 thick bars (8 servings) 1x
const share_pin_buttons = document.getElementsByClassName( ‘share-pin button’ ); if ( share_pin_buttons ) { for ( let share_key = 0; share_key { e.stopPropagation(); window.open(e.target.dataset.href,’targetWindow’,’toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=500′); return false; } ); } }

Description

The authentic viral homemade copycat of the famous FIX Dubai chocolate bar. Featuring thick glossy tempered chocolate stuffed with shatteringly crisp butter-toasted kataifi pastry shreds drenched in rich pistachio cream and nutty tahini.


Ingredients

Scale
  • 280g (10 oz) high-quality milk or dark chocolate (or 50/50 blend), finely chopped
  • 150g (5.3 oz) kataifi pastry (shredded phyllo dough), finely chopped
  • 35g (2.5 tbsp) unsalted European-style butter
  • 180g (3/4 cup) 100% pure pistachio cream or pistachio paste
  • 25g (1.5 tbsp) pure runny tahini paste
  • 1 pinch fine sea salt or flaky Maldon salt
  • Optional: edible gold dust or white chocolate colored with matcha for decorating molds

Instructions

  1. Toast the Kataifi: Melt unsalted butter in a wide skillet over medium heat. Add finely chopped kataifi pastry and toast gently, stirring continuously for 8 to 10 minutes until evenly radiant golden-brown and fragrant. Transfer immediately to a mixing bowl and let cool for 5 minutes.
  2. Make the Pistachio Knafeh Filling: Pour pistachio cream, tahini, and a pinch of salt over the toasted kataifi. Fold gently with a spatula until every crunchy shred is thoroughly coated in creamy emerald-green goodness.
  3. Melt & Paint the Chocolate Shell: Melt two-thirds of your chopped chocolate using a double boiler (bain-marie) or in gentle 20-second microwave bursts. Stir in the remaining chocolate off-heat until smooth and tempered. Pour a layer into your deep silicone chocolate bar molds, brushing the chocolate up all sides. Chill in the freezer for 8 minutes to firm.
  4. Layer the Filling: Generously pack the cooled pistachio knafeh filling into each chocolate shell, leaving a 2mm gap at the top. Smooth evenly with an offset spatula.
  5. Cap and Seal: Pour the remaining melted chocolate over the filling to cap the bar, smoothing gently with a bench scraper or spatula.
  6. Set and Demold: Refrigerate for 25 to 30 minutes until the chocolate snaps cleanly away from the silicone mold. Invert, snap open, and enjoy the ultimate viral crunch!

Notes

Ensure the toasted kataifi cools slightly before combining with pistachio cream to retain maximum crunchiness. Store bars at room temperature for up to 10 days or in an airtight container in the fridge for up to 3 weeks.

  • Prep Time: 15 mins
  • Cook Time: 10 mins
  • Category: Dessert
  • Cuisine: Middle Eastern Fusion

Nutrition

  • Calories: 395
window.trCommon={“minRating”:6,”ajaxurl”:”https://felisrecipes.com/wp-admin/admin-ajax.php”,”ratingNonce”:””,”postId”:12689}; window.TastyRecipes = window.TastyRecipes || {}; window.TastyRecipes.smoothScroll = { init() { document.addEventListener( ‘click’, ( e ) => { let anchor = e.target; if ( anchor.tagName !== ‘A’ ) { anchor = anchor.closest( ‘a.tasty-recipes-scrollto’ ); } if ( ! anchor || ! anchor.classList.contains( ‘tasty-recipes-scrollto’ ) ) { return; } const elementHref = anchor.getAttribute( ‘href’ ); if ( ! elementHref ) { return; } e.preventDefault(); this.goToSelector( elementHref ); }); }, goToSelector( selector ) { const element = document.querySelector( selector ); if ( ! element ) { return; } element.scrollIntoView( { behavior: ‘smooth’ } ); } }; document.addEventListener( ‘DOMContentLoaded’, () => window.TastyRecipes.smoothScroll.init() ); (function(){ var bothEquals = function( d1, d2, D ) { var ret = 0; if (d1<=D) { ret++; } if (d2<=D) { ret++; } return ret === 2; }; var frac =function frac(x,D,mixed){var n1=Math.floor(x),d1=1;var n2=n1+1,d2=1;if(x!==n1){while(bothEquals(d1,d2,D)){var m=(n1+n2)/(d1+d2);if(x===m){if(d1+d2d2){d2=D+1;}else {d1=D+1;}break}else if(xD){d1=d2;n1=n2}if(!mixed){return[0,n1,d1];}var q=Math.floor(n1/d1);return[q,n1-q*d1,d1]};frac.cont=function cont(x,D,mixed){var sgn=x<0?-1:1;var B=x*sgn;var P_2=0,P_1=1,P=0;var Q_2=1,Q_1=0,Q=0;var A=Math.floor(B);while(Q_1<D){A=Math.floor(B);P=A*P_1+P_2;Q=A*Q_1+Q_2;if(B-AD){if(Q_1>D){Q=Q_2;P=P_2}else{Q=Q_1;P=P_1}}if(!mixed){return[0,sgn*P,Q];}var q=Math.floor(sgn*P/Q);return[q,sgn*P-q*Q,Q]}; window.tastyRecipesVulgarFractions = JSON.parse(decodeURIComponent(“%7B%22%C2%BC%22%3A%221%2F4%22%2C%22%C2%BD%22%3A%221%2F2%22%2C%22%C2%BE%22%3A%223%2F4%22%2C%22%E2%85%93%22%3A%221%2F3%22%2C%22%E2%85%94%22%3A%222%2F3%22%2C%22%E2%85%95%22%3A%221%2F5%22%2C%22%E2%85%96%22%3A%222%2F5%22%2C%22%E2%85%97%22%3A%223%2F5%22%2C%22%E2%85%98%22%3A%224%2F5%22%2C%22%E2%85%99%22%3A%221%2F6%22%2C%22%E2%85%9A%22%3A%225%2F6%22%2C%22%E2%85%9B%22%3A%221%2F8%22%2C%22%E2%85%9C%22%3A%223%2F8%22%2C%22%E2%85%9D%22%3A%225%2F8%22%2C%22%E2%85%9E%22%3A%227%2F8%22%7D”)); window.tastyRecipesFormatAmount = function(amount, el) { if ( parseFloat( amount ) === parseInt( amount ) ) { return amount; } var roundType = ‘frac’; if (typeof el.dataset.amountShouldRound !== ‘undefined’) { if (‘false’ !== el.dataset.amountShouldRound) { if ( ‘number’ === el.dataset.amountShouldRound ) { roundType = ‘number’; } else if (‘frac’ === el.dataset.amountShouldRound) { roundType = ‘frac’; } else if (‘vulgar’ === el.dataset.amountShouldRound) { roundType = ‘vulgar’; } else { roundType = ‘integer’; } } } if (‘number’ === roundType) { amount = Number.parseFloat(amount).toPrecision(2); } else if (‘integer’ === roundType) { amount = Math.round(amount); } else if (‘frac’ === roundType || ‘vulgar’ === roundType) { var denom = 8; if (typeof el.dataset.unit !== ‘undefined’) { var unit = el.dataset.unit; if ([‘cups’,’cup’,’c’].includes(unit)) { denom = 4; if (0.125 === amount) { denom = 8; } if (“0.1667″ === Number.parseFloat( amount ).toPrecision(4)) { denom = 6; } } if ([‘tablespoons’,’tablespoon’,’tbsp’].includes(unit)) { denom = 2; } if ([‘teaspoons’,’teaspoon’,’tsp’].includes(unit)) { denom = 8; } } var amountArray = frac.cont( amount, denom, true ); var newAmount = ”; if ( amountArray[1] !== 0 ) { newAmount = amountArray[1] + ‘/’ + amountArray[2]; if (‘vulgar’ === roundType) { Object.keys(window.tastyRecipesVulgarFractions).forEach(function(vulgar) { if (newAmount === window.tastyRecipesVulgarFractions[vulgar]) { newAmount = vulgar; } }); } } if ( newAmount ) { newAmount = ‘ ‘ + newAmount; } if ( amountArray[0] ) { newAmount = amountArray[0] + newAmount; } amount = newAmount; } return amount; }; window.tastyRecipesUpdatePrintLink = () => { const printButton = document.querySelector( ‘.tasty-recipes-print-button’ ); if ( ! printButton ) { return; } const printURL = new URL( printButton.href ); const searchParams = new URLSearchParams( printURL.search ); const unitButton = document.querySelector( ‘.tasty-recipes-convert-button-active’ ); const scaleButton = document.querySelector( ‘.tasty-recipes-scale-button-active’ ); let unit = ”; let scale = ”; if ( unitButton ) { unit = unitButton.dataset.unitType; searchParams.delete(‘unit’); searchParams.set( ‘unit’, unit ); } if ( scaleButton ) { scale = scaleButton.dataset.amount; searchParams.set( ‘scale’, scale ); } const paramString = searchParams.toString(); const newURL = ” === paramString ? printURL.href : printURL.origin + printURL.pathname + ‘?’ + paramString; const printLinks = document.querySelectorAll( ‘.tasty-recipes-print-link’ ); printLinks.forEach( ( el ) => { el.href = newURL; }); const printButtons = document.querySelectorAll( ‘.tasty-recipes-print-button’ ); printButtons.forEach( ( el ) => { el.href = newURL; }); }; document.addEventListener( ‘DOMContentLoaded’, () => { if ( ! window.location.href.includes( ‘/print/’ ) ) { return; } const searchParams = new URLSearchParams( window.location.search ); const unit = searchParams.get( ‘unit’ ); const scale = searchParams.get( ‘scale’ ); if ( unit && ( ‘metric’ === unit || ‘usc’ === unit ) ) { document.querySelector( ‘.tasty-recipes-convert-button[data-unit-type=”‘ + unit + ‘”]’ ).click(); } if ( scale && Number(scale) > 0 ) { document.querySelector( ‘.tasty-recipes-scale-button[data-amount=”‘ + Number(scale) + ‘”]’ ).click(); } }); }()); (function(){ var buttonClass = ‘tasty-recipes-scale-button’, buttonActiveClass = ‘tasty-recipes-scale-button-active’, buttons = document.querySelectorAll(‘.tasty-recipes-scale-button’); if ( ! buttons ) { return; } buttons.forEach(function(button){ button.addEventListener(‘click’, function(event){ event.preventDefault(); var recipe = event.target.closest(‘.tasty-recipes’); if ( ! recipe ) { return; } var otherButtons = recipe.querySelectorAll(‘.’ + buttonClass); otherButtons.forEach(function(bt){ bt.classList.remove(buttonActiveClass); }); button.classList.add(buttonActiveClass); var scalables = recipe.querySelectorAll(‘span[data-amount]’); var buttonAmount = parseFloat( button.dataset.amount ); scalables.forEach(function(scalable){ if (typeof scalable.dataset.amountOriginalType === ‘undefined’ && typeof scalable.dataset.nfOriginal === ‘undefined’) { if (-1 !== scalable.innerText.indexOf(‘/’)) { scalable.dataset.amountOriginalType = ‘frac’; } if (-1 !== scalable.innerText.indexOf(‘.’)) { scalable.dataset.amountOriginalType = ‘number’; } Object.keys(window.tastyRecipesVulgarFractions).forEach(function(vulgar) { if (-1 !== scalable.innerText.indexOf(vulgar)) { scalable.dataset.amountOriginalType = ‘vulgar’; } }); if (typeof scalable.dataset.amountOriginalType !== ‘undefined’) { scalable.dataset.amountShouldRound = scalable.dataset.amountOriginalType; } } var amount = parseFloat( scalable.dataset.amount ) * buttonAmount; amount = window.tastyRecipesFormatAmount(amount, scalable); if ( typeof scalable.dataset.unit !== ‘undefined’ ) { if ( ! scalable.classList.contains(‘nutrifox-quantity’) ) { if ( ! scalable.classList.contains(‘nutrifox-second-quantity’) ) { amount += ‘ ‘ + scalable.dataset.unit; } } } scalable.innerText = amount; }); var nonNumerics = recipe.querySelectorAll(‘[data-has-non-numeric-amount]’); nonNumerics.forEach(function(nonNumeric){ var indicator = nonNumeric.querySelector(‘span[data-non-numeric-label]’); if ( indicator ) { nonNumeric.removeChild(indicator); } if ( 1 !== buttonAmount ) { indicator = document.createElement(‘span’); indicator.setAttribute(‘data-non-numeric-label’, true); var text = document.createTextNode(‘ (x’ + buttonAmount + ‘)’); indicator.appendChild(text); nonNumeric.appendChild(indicator); } }); window.tastyRecipesUpdatePrintLink(); }); }); }()); (function() { document.querySelectorAll(‘.tasty-recipes-copy-button’).forEach(function(copyButton) { if (copyButton.getAttribute(‘data-tasty-recipes-click-event’)) { return; } copyButton.setAttribute(‘data-tasty-recipes-click-event’, true); copyButton.addEventListener(‘click’, function(event) { event.preventDefault(); var copyContainer = copyButton.closest(‘.tasty-recipes-ingredients-clipboard-container’); var messageText = copyButton.attributes.getNamedItem(‘data-success’).nodeValue; var copySuccessMessage = document.createElement(‘div’); var copySuccessParagraph = document.createElement(‘p’); copySuccessParagraph.innerText = messageText; copySuccessMessage.appendChild(copySuccessParagraph); copySuccessMessage.classList.add(‘tasty-recipes-flash-message’); var messageDuration = 3000; var ingredients = []; var ingredientsContainer = copyButton.closest(‘.tasty-recipes-ingredients’) || copyButton.closest(‘.tasty-recipe-ingredients’); var foundIngredients = false; var findIngredients = function(div) { if ( div.querySelectorAll(‘li’).length ) { div.querySelectorAll(‘li’).forEach(function(li) { ingredients.push(li.innerText); }); foundIngredients = true; } else if ( div.querySelectorAll(‘p’).length ) { div.querySelectorAll(‘p’).forEach(function(p) { ingredients.push(p.innerText); }); foundIngredients = true; } }; if (ingredientsContainer.querySelector(‘.tasty-recipes-ingredients-body’)) { findIngredients(ingredientsContainer.querySelector(‘.tasty-recipes-ingredients-body’)); } else { ingredientsContainer.querySelectorAll(‘div’).forEach(function(div) { if ( foundIngredients ) { return; } if ( div.classList.contains(‘tasty-recipes-ingredients-header’) || div.parentElement.classList.contains(‘tasty-recipes-ingredients-header’) || div.classList.contains(‘tasty-recipes-ingredients-header’) ) { return; } findIngredients(div); }); } var readableIngredients = ”; ingredients.forEach(function(ingredient) { readableIngredients += ingredient + ‘n’; }); readableIngredients = readableIngredients.trim(); var fakeElem = document.createElement(“textarea”); fakeElem.style.fontSize = “12pt”; fakeElem.style.border = “0”; fakeElem.style.padding = “0”; fakeElem.style.margin = “0”; fakeElem.style.position = “absolute”; fakeElem.style.left = “-9999px”; var yPosition = window.pageYOffset || document.documentElement.scrollTop; fakeElem.style.top = yPosition + ‘px’; fakeElem.setAttribute(“readonly”, “”); fakeElem.value = readableIngredients; document.body.appendChild(fakeElem); if (navigator.userAgent.match(/ipad|iphone/i)) { var range = document.createRange(); var selection = window.getSelection(); range.selectNodeContents(fakeElem); selection.removeAllRanges(); selection.addRange(range); fakeElem.setSelectionRange(0, 999999); } else { fakeElem.select(); } document.execCommand(“copy”); document.body.removeChild(fakeElem); fakeElem = null; copyContainer.appendChild(copySuccessMessage); setTimeout(function() { copyContainer.removeChild(copySuccessMessage); }, messageDuration); }); }); }()); (function(){ document.querySelectorAll(‘[data-tr-ingredient-checkbox]’).forEach(function(el) { var input = el.querySelector(‘.tr-ingredient-checkbox-container input[type=”checkbox”]’); if ( ! input ) { return; } if (input.checked) { el.dataset.trIngredientCheckbox = ‘checked’; } el.addEventListener(‘click’, function(event) { if ( ‘A’ === event.target.nodeName || ‘INPUT’ === event.target.nodeName || ‘LABEL’ === event.target.nodeName ) { return; } input.click(); }); input.addEventListener(‘change’, function() { el.dataset.trIngredientCheckbox = input.checked ? ‘checked’ : ”; }); }); }()); window.TastyRecipes = window.TastyRecipes || {}; window.TastyRecipes.staticTooltip = { element: null, tooltipElement: null, deleting: false, init( element ) { if ( this.deleting ) { return; } this.element = element; this.buildElements(); }, destroy() { if ( ! this.tooltipElement || this.deleting ) { return; } this.deleting = true; this.tooltipElement.classList.remove( ‘opened’ ); setTimeout( () => { this.tooltipElement.remove(); this.deleting = false; }, 500 ); }, buildElements() { const tooltipElement = document.createElement( ‘div’ ); tooltipElement.classList.add( ‘tasty-recipes-static-tooltip’); tooltipElement.setAttribute( ‘id’, ‘tasty-recipes-tooltip’ ); const currentTooltipElement = document.getElementById( ‘tasty-recipes-tooltip’ ); if ( currentTooltipElement ) { document.body.replaceChild( tooltipElement, currentTooltipElement ); } else { document.body.appendChild( tooltipElement ); } this.tooltipElement = document.getElementById( ‘tasty-recipes-tooltip’ ); }, show() { if ( ! this.tooltipElement ) { return; } const tooltipTop = this.element.getBoundingClientRect().top + window.scrollY – 10 // 10px offset. – this.tooltipElement.getBoundingClientRect().height; const tooltipLeft = this.element.getBoundingClientRect().left – ( this.tooltipElement.getBoundingClientRect().width / 2 ) + ( this.element.getBoundingClientRect().width / 2 ) – 1; const posLeft = Math.max( 10, tooltipLeft ); this.maybeRemoveTail( posLeft !== tooltipLeft ); this.tooltipElement.setAttribute( ‘style’, ‘top:’ + tooltipTop + ‘px;left:’ + posLeft + ‘px;’ ); this.tooltipElement.classList.add( ‘opened’ ); }, maybeRemoveTail( removeTail ) { if ( removeTail ) { this.tooltipElement.classList.add( ‘tr-hide-tail’ ); } else { this.tooltipElement.classList.remove( ‘tr-hide-tail’ ); } }, changeMessage( message ) { if ( ! this.tooltipElement ) { return; } this.tooltipElement.innerHTML = message; } }; window.TastyRecipes.ajax = { sendPostRequest( url, data, success, failure ) { const xhr = new XMLHttpRequest(); xhr.open( ‘POST’, url, true ); xhr.send( this.preparePostData( data ) ); xhr.onreadystatechange = () => { if ( 4 !== xhr.readyState ) { return; } if ( xhr.status === 200 ) { success( JSON.parse( xhr.responseText ) ); return; } failure( xhr ); }; xhr.onerror = () => { failure( xhr ); }; }, preparePostData( data ) { const formData = new FormData(); for ( const key in data ) { formData.append( key, data[key] ); } return formData; }, }; window.TastyRecipes.ratings = { defaultRating: 0, currentRatingPercentage: 100, savingRating: false, init( minRating ) { this.minRating = minRating; this.formWatchRating(); this.closeTooltipWhenClickOutside(); this.addBodyClassBasedOnSelectedRating(); this.backwardCompFormRatingPosition(); }, formWatchRating() { const ratings = document.querySelectorAll(‘.tasty-recipes-no-ratings-buttons [data-rating]’); if ( ratings.length { event.preventDefault(); this.defaultRating = event.target.closest( ‘.checked’ ).dataset.rating; this.setCheckedStar( event.target ); this.maybeSendRating( this.defaultRating, event.target ); this.setRatingInForm( this.defaultRating ); } ); } }, closeTooltipWhenClickOutside() { window.addEventListener( ‘click’, e => { // Bailout (don’t remove the tooltip) when the clicked element is a rating star, or it’s the tooltip itself. if ( e.target.closest( ‘.tasty-recipes-rating’ ) || e.target.classList.contains( ‘tasty-recipes-static-tooltip’ ) ) { return; } window.TastyRecipes.staticTooltip.destroy(); } ); }, setRatingInForm( rating ) { const ratingInput = document.querySelector( ‘#respond .tasty-recipes-rating[value=”‘ + rating + ‘”]’ ); if ( ! ratingInput ) { return; } ratingInput.click(); }, addBodyClassBasedOnSelectedRating() { const ratingInputs = document.querySelectorAll( ‘input.tasty-recipes-rating’ ); if ( ! ratingInputs ) { return; } for ( const ratingInput of ratingInputs ) { ratingInput.addEventListener( ‘click’, currentEvent => { const selectedRating = currentEvent.target.getAttribute( ‘value’ ); this.handleBodyClassByRating( selectedRating ); this.toggleCommentTextareaRequired( selectedRating ); } ); } }, handleBodyClassByRating( rating ) { if ( rating < this.minRating ) { document.body.classList.remove( 'tasty-recipes-selected-minimum-rating' ); return; } document.body.classList.add( 'tasty-recipes-selected-minimum-rating' ); }, toggleCommentTextareaRequired( rating ) { const commentTextarea = document.getElementById( 'comment' ); if ( ! commentTextarea ) { return; } if ( rating { window.TastyRecipes.staticTooltip.changeMessage( response.data.message ); window.TastyRecipes.staticTooltip.show(); this.updateAverageText( response.data, recipeCardElement ); this.maybeFillCommentForm( response.data ); // Hide the tooltip after 5 seconds. setTimeout( () => { this.maybeResetTooltip( recipeCardElement, response.data, rating ); }, 5000 ); }, () => { this.resetTooltip( recipeCardElement ); } ); }, updateAverageText( data, recipeCardElement ) { if ( ! data.average ) { return; } this.setRatingPercent( data ); if ( ! data.count ) { return; } const quickLink = document.querySelector( ‘.tasty-recipes-rating-link’ ); if ( quickLink ) { this.setTextInContainer( quickLink, data ); this.setPartialStar( quickLink ); } const cardStars = recipeCardElement.querySelector( ‘.tasty-recipes-ratings-buttons’ ); cardStars.dataset.trDefaultRating = data.average; this.setTextInContainer( recipeCardElement.querySelector( ‘.tasty-recipes-rating’ ), data ); }, setTextInContainer( container, data ) { if ( ! container ) { return; } if ( data.label ) { const ratingLabelElement = container.querySelector( ‘.rating-label’ ); if ( ratingLabelElement ) { ratingLabelElement.innerHTML = data.label; } return; } const averageElement = container.querySelector( ‘.average’ ); if ( averageElement ) { averageElement.textContent = data.average; } const countElement = container.querySelector( ‘.count’ ); if ( countElement ) { countElement.textContent = data.count; } }, setPartialStar( container ) { const highestStar = container.querySelector( ‘[data-rating=”‘ + Math.ceil( this.defaultRating ) + ‘”]’ ); if ( highestStar ) { highestStar.dataset.trClip = this.currentRatingPercentage; } }, setRatingPercent( data ) { this.defaultRating = data.average.toFixed( 1 ); const parts = data.average.toFixed( 2 ).toString().split( ‘.’ ); this.currentRatingPercentage = parts[1] ? parts[1] : 100; if ( this.currentRatingPercentage === ’00’ ) { this.currentRatingPercentage = 100; } }, setCheckedStar( target ) { const cardRatingContainer = target.closest( ‘.tasty-recipes-ratings-buttons’ ); const selectedRatingElement = cardRatingContainer.querySelector( ‘[data-tr-checked]’ ); if ( selectedRatingElement ) { delete selectedRatingElement.dataset.trChecked; } const thisStar = target.closest( ‘.tasty-recipes-rating’ ); thisStar.dataset.trChecked = 1; thisStar.querySelector( ‘[data-tr-clip]’ ).dataset.trClip = 100; }, maybeFillCommentForm( data ) { if ( ! data.comment || ! data.comment.content ) { return; } const commentForm = document.querySelector( ‘#commentform’ ); if ( ! commentForm ) { return; } const commentBox = commentForm.querySelector( ‘[name=comment]’ ); if ( ! commentBox || commentBox.value ) { return; } // Add comment details for editing. commentBox.innerHTML = data.comment.content; if ( data.comment.name ) { commentForm.querySelector( ‘[name=author]’ ).value = data.comment.name; commentForm.querySelector( ‘[name=email]’ ).value = data.comment.email; } }, maybeResetTooltip( recipeCardElement, data, rating ) { if ( this.savingRating === rating ) { this.resetTooltip( recipeCardElement, data ); } }, resetTooltip( recipeCardElement, data ) { window.TastyRecipes.staticTooltip.destroy(); this.savingRating = false; // Reset the default rating. const cardRatingContainer = recipeCardElement.querySelector( ‘.tasty-recipes-ratings-buttons’ ); if ( cardRatingContainer ) { this.defaultRating = ( data && data.average ) ? data.average.toFixed(1) : cardRatingContainer.dataset.trDefaultRating; cardRatingContainer.dataset.trDefaultRating = this.defaultRating; this.resetSelectedStar( cardRatingContainer, data ); } }, resetSelectedStar( cardRatingContainer ) { const selectedRatingElement = cardRatingContainer.querySelector( ‘[data-rating=”‘ + Math.ceil( this.defaultRating ) + ‘”]’ ); if ( selectedRatingElement ) { selectedRatingElement.querySelector( ‘[data-tr-clip]’ ).dataset.trClip = this.currentRatingPercentage; selectedRatingElement.parentNode.dataset.trChecked = 1; } const previousSelectedElement= cardRatingContainer.querySelector( ‘[data-tr-checked]’ ); if ( previousSelectedElement ) { const currentSelectedRating = previousSelectedElement.querySelector(‘[data-rating]’); if ( currentSelectedRating !== selectedRatingElement ) { delete previousSelectedElement.dataset.trChecked; } } }, backwardCompFormRatingPosition() { const ratingsButtons = document.querySelector( ‘#respond .tasty-recipes-ratings-buttons, #tasty-recipes-comment-rating .tasty-recipes-ratings-buttons’ ); if ( ! ratingsButtons ) { return; } const ratingsButtonsStyles = window.getComputedStyle(ratingsButtons); if ( ! ratingsButtonsStyles.display.includes( ‘flex’ ) ) { ratingsButtons.style.direction = ‘rtl’; } if ( typeof tastyRecipesRating !== ‘undefined’ ) { // Select the rating that was previously selected in admin. ratingsButtons.querySelector( ‘.tasty-recipes-rating[value=”‘ + tastyRecipesRating + ‘”]’ ).checked = true; } const ratingSpans = ratingsButtons.querySelectorAll( ‘.tasty-recipes-rating’ ); for (const ratingSpan of ratingSpans) { ratingSpan.addEventListener( ‘click’, event => { if ( ratingSpan === event.target ) { return; } ratingSpan.previousElementSibling.click(); } ); } } }; (function(callback) { if (document.readyState !== “loading”) { callback(); } else { window.addEventListener( ‘load’, callback ); } })(() => { window.TastyRecipes.ratings.init( window.trCommon ? window.trCommon.minRating : 4 ); });

Similar Posts