If you’re looking for a show-stopping dessert that’s both delicious and easy to make, you’re going to adore this Moist Carrot Bundt Cake! It’s a delightful twist on the classic carrot cake, featuring all those warm spices that fill your kitchen with comforting aromas. This cake is perfect for family gatherings, afternoon tea, or simply as a sweet treat to brighten your day. With its elegant Bundt shape and creamy glaze drizzled on top, it’s bound to impress everyone at the table!

This recipe has become a beloved staple in my home because it’s not just tasty; it’s also incredibly moist and tender. Plus, it’s versatile enough to serve on any occasion—be it a cozy Sunday brunch or a festive celebration.


Why You’ll Love This Recipe
- Easy to make: With simple steps and common ingredients, you’ll whip this up in no time!
- Perfectly moist: The combination of grated carrots and pineapple keeps the cake wonderfully soft.
- Family-friendly: Everyone loves carrot cake, and this version is sure to be a hit with kids and adults alike.
- Make-ahead option: Bake it ahead of time and store it; the flavors only get better as it sits!
- Gorgeous presentation: The Bundt shape adds an elegant touch that makes it great for special occasions.
Ingredients You’ll Need
You’ll find that these ingredients are simple and wholesome—most of them might already be in your pantry! Here’s what you need for the Moist Carrot Bundt Cake:
For the Cake
- 2 cups finely grated carrots (about 3 medium-sized carrots)
- 1 cup canned pineapple
- 2¼ cups all-purpose flour (plain flour in the UK)
- ¼ cup cornstarch
- 2 tsps baking powder
- ½ tsp baking soda
- ½ tsp salt
- 2½ tsps cinnamon (ground)
- 1¾ tsps ginger (ground/powdered)
- ¼ tsp cloves (ground)
- ½ tsp nutmeg (ground)
- 1½ cups soft brown sugar (firmly packed)
- 3 large eggs (room temperature)
- 1 cup unflavoured vegetable oil (I use canola)
- 3 tsps vanilla essence/extract
- ½ cup yoghurt (unsweetened, regular not Greek)
- 1 cup pecans or walnuts (coarsely chopped; I like to use both)
For the Cream Cheese Glaze
- 2 cups powdered sugar (also known as icing/confectioners’ sugar)
- 2 tsps unsalted butter (melted)
- ½ tsp vanilla extract/essence
- ¾ cup cream cheese (room temp)
Variations
This Moist Carrot Bundt Cake recipe is flexible, allowing you to customize it based on your taste preferences or dietary needs. Here are some fun variations:
- Add dried fruits: Mix in some raisins or currants for an extra burst of sweetness.
- Go nut-free: Swap out nuts with seeds like sunflower or pumpkin seeds for crunch without the allergens.
- Spice it up: Add a pinch of cayenne or chili powder for a spicy-sweet kick that’s truly unique!
- Vegan twist: Substitute eggs with flaxseed meal mixed with water and use plant-based yogurt for a delicious vegan version.
How to Make Moist Carrot Bundt Cake
Step 1: Preheat Your Oven
Start by preheating your oven to 350°F (175°C). This ensures that your cake bakes evenly from the moment you put it in. Grease your Bundt pan well with vegetable oil or cooking spray so that the cake releases easily after baking.
Step 2: Mix Dry Ingredients
In a large bowl, whisk together all your dry ingredients: flour, cornstarch, baking powder, baking soda, salt, cinnamon, ginger, cloves, and nutmeg. Mixing these dry components first allows them to combine evenly and ensures that your cake rises beautifully!
Step 3: Combine Wet Ingredients
In another bowl, beat together the brown sugar and eggs until light and fluffy. Then add the vegetable oil, vanilla essence, yoghurt, and grated carrots along with the canned pineapple. Stir until everything is well combined; this mixture will create that lovely moisture in our cake!
Step 4: Combine Wet and Dry Mixtures
Gradually add your dry ingredient mixture into the wet mixture. Gently fold until just combined—be careful not to overmix! A few lumps are perfectly fine; they will bake out during cooking.
Step 5: Add Nuts
Fold in those coarsely chopped pecans or walnuts at this stage. They’ll give wonderful texture and flavor throughout your cake.
Step 6: Bake
Pour the batter into your prepared Bundt pan and spread it evenly. Bake in the preheated oven for about 45 minutes or until a toothpick inserted comes out clean. Keep an eye on it towards the end of baking!
Step 7: Cool & Glaze
Once baked, allow your cake to cool in the pan for about 10 minutes before transferring it onto a wire rack. Meanwhile, prepare your cream cheese glaze by mixing together powdered sugar, melted butter, vanilla extract, and room temperature cream cheese until smooth. Drizzle over the cooled cake before serving.
And there you have it—a Moist Carrot Bundt Cake that’s sure to be loved by all! Enjoy every slice!
Pro Tips for Making Moist Carrot Bundt Cake
Baking is an art, and with a few handy tips, you can ensure your Moist Carrot Bundt Cake turns out perfectly every time!
- Use room temperature ingredients: Ingredients like eggs and yogurt blend more easily when they are at room temperature, resulting in a smoother batter and a more tender cake.
- Don’t overmix the batter: Mixing just until combined helps to maintain the cake’s moisture and fluffy texture. Overmixing can lead to a denser cake.
- Grease the Bundt pan generously: Make sure to thoroughly grease your pan to prevent sticking. A well-greased pan allows for easy release and maintains the cake’s beautiful shape.
- Check for doneness with a toothpick: Insert a toothpick into the center; if it comes out clean or with a few moist crumbs, your cake is ready. This prevents over-baking, which can dry it out.
- Let it cool before glazing: Allowing your cake to cool completely before adding the cream cheese glaze ensures that it stays intact and doesn’t melt into puddles.
How to Serve Moist Carrot Bundt Cake
Presenting your Moist Carrot Bundt Cake is just as important as making it! Here are some delightful ideas to make your dessert shine.
Garnishes
- Chopped nuts: Sprinkle some coarsely chopped pecans or walnuts on top of the glaze for added texture and a nutty flavor.
- Fresh herbs: Add a touch of freshness by garnishing with sprigs of mint or edible flowers. They provide a lovely visual contrast.
- Zest: A light dusting of orange or lemon zest on top will brighten up the flavors and give your cake a vibrant look.
Side Dishes
- Whipped coconut cream: Light and airy, this dairy-free alternative adds sweetness and creaminess that complements the spices in the cake perfectly.
- Fruit salad: A refreshing mix of seasonal fruits offers a nice contrast to the rich cake. The natural sweetness of fruit balances well with its spices.
- Tea or coffee: Serving your cake with a warm cup of chai or freshly brewed coffee enhances its cozy vibes, making it perfect for afternoon tea.
- Ice cream: A scoop of vanilla or coconut ice cream on the side provides a delightful creaminess that pairs beautifully with the moistness of the cake.
Make Ahead and Storage
This Moist Carrot Bundt Cake is perfect for meal prep, allowing you to enjoy this delightful dessert over several days without losing its charm.
Storing Leftovers
- Wrap leftover cake tightly in plastic wrap or store it in an airtight container.
- Keep it at room temperature for up to 3 days, or refrigerate for up to a week.
Freezing
- Allow the cake to cool completely before freezing.
- Wrap it tightly in plastic wrap and then place it in a freezer-safe bag. It can be frozen for up to 3 months.
- For best results, freeze without the cream cheese glaze; add it after thawing.
Reheating
- Thaw the cake overnight in the refrigerator if frozen.
- To serve warm, microwave individual slices for about 15-20 seconds or until heated through.
FAQs
Can I make this Moist Carrot Bundt Cake gluten-free?
Yes! To make a gluten-free version, substitute all-purpose flour with a gluten-free flour blend that includes xanthan gum.
How can I ensure my Moist Carrot Bundt Cake stays moist?
Using fresh grated carrots and proper storage techniques will help maintain moisture. Avoid overbaking, as this can dry out the cake.
What are some variations of the Moist Carrot Bundt Cake?
You can add raisins, coconut flakes, or even swap nuts for chocolate chips to switch things up.
Final Thoughts
This Moist Carrot Bundt Cake is not just a treat; it’s a labor of love that brings warmth and joy to any gathering. I hope you enjoy making this recipe as much as I do! Feel free to experiment with your favorite additions and share this delightful cake with friends and family. Happy baking!
Moist Carrot Bundt Cake
Experience the joy of baking with this Moist Carrot Bundt Cake, a delightful and easy-to-make dessert that’s perfect for any occasion. This cake combines the natural sweetness of grated carrots and juicy pineapple, infused with warm spices like cinnamon and nutmeg, creating an inviting aroma that fills your kitchen. Topped with a creamy glaze, this Bundt cake is not only visually stunning but also incredibly moist and tender. Whether you’re hosting a family gathering or enjoying a cozy afternoon tea, this cake is sure to impress and satisfy all taste buds. Plus, it’s versatile enough to adapt to your preferences, making it a beloved staple in any home.
- Prep Time: 20 minutes
- Cook Time: 45 minutes
- Total Time: 1 hour 5 minutes
- Yield: Approximately 12 servings 1x
- Category: Dessert
- Method: Baking
- Cuisine: American
Ingredients
Scale
- 2 cups finely grated carrots
- 1 cup canned pineapple
- 2¼ cups all-purpose flour
- ¼ cup cornstarch
- 2 tsps baking powder
- ½ tsp baking soda
- ½ tsp salt
- 2½ tsps cinnamon (ground)
- 1¾ tsps ginger (ground/powdered)
- ¼ tsp cloves (ground)
- ½ tsp nutmeg (ground)
- 1½ cups soft brown sugar
- 3 large eggs
- 1 cup unflavoured vegetable oil
- 3 tsps vanilla essence/extract
- ½ cup yoghurt
- 1 cup pecans or walnuts (coarsely chopped)
- 2 cups powdered sugar
- 2 tsps unsalted butter (melted)
- ½ tsp vanilla extract
- ¾ cup cream cheese
Instructions
- Preheat your oven to 350°F (175°C) and grease a Bundt pan.
- In a large bowl, whisk together flour, cornstarch, baking powder, baking soda, salt, and spices.
- In another bowl, beat brown sugar and eggs until fluffy. Add vegetable oil, vanilla essence, yogurt, grated carrots, and pineapple; mix well.
- Gradually combine wet and dry ingredients until just blended; fold in nuts.
- Pour into the prepared pan and bake for about 45 minutes or until a toothpick comes out clean.
- Cool for 10 minutes before transferring to a wire rack. Prepare the glaze by mixing powdered sugar, melted butter, vanilla extract, and cream cheese; drizzle over cooled cake.
Nutrition
- Serving Size: 1 slice (70g)
- Calories: 250
- Sugar: 18g
- Sodium: 150mg
- Fat: 12g
- Saturated Fat: 2g
- Unsaturated Fat: 10g
- Trans Fat: 0g
- Carbohydrates: 34g
- Fiber: 1g
- Protein: 3g
- Cholesterol: 30mg
window.trCommon={“minRating”:6,”ajaxurl”:”https:\/\/www.kitchenstorydaily.com\/wp-admin\/admin-ajax.php”,”ratingNonce”:”9e255ceb7a”,”postId”:6001};
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();
});
});
}());
window.TastyRecipes = window.TastyRecipes || {};
window.TastyRecipes.cookMode = {
wakeLockApi: false,
wakeLock: false,
cookModeSelector: ‘.tasty-recipes-cook-mode’,
init() {
if (“wakeLock” in navigator && “request” in navigator.wakeLock) {
this.wakeLockApi = navigator.wakeLock;
}
const cookModes = document.querySelectorAll(this.cookModeSelector);
if (cookModes.length > 0) {
for (const cookMode of cookModes) {
if (this.wakeLockApi) {
cookMode.querySelector(‘input[type=”checkbox”]’).addEventListener(“change”, event => {
this.checkboxChange(event.target);
}, false);
} else {
cookMode.style.display = “none”;
}
}
}
},
checkboxChange(checkbox) {
if (checkbox.checked) {
this.lock();
} else {
this.unlock();
}
},
setCheckboxesState(state) {
const checkboxes = document.querySelectorAll(this.cookModeSelector + ‘ input[type=”checkbox”]’);
for (const checkbox of checkboxes) {
checkbox.checked = state;
}
},
async lock() {
try {
this.wakeLock = await this.wakeLockApi.request(“screen”);
this.wakeLock.addEventListener(“release”, () => {
this.wakeLock = false;
this.setCheckboxesState(false);
});
this.setCheckboxesState(true);
} catch (error) {
this.setCheckboxesState(false);
}
},
unlock() {
if (this.wakeLock) {
this.wakeLock.release();
this.wakeLock = false;
}
this.setCheckboxesState(false);
}
};
(function(callback) {
if (document.readyState !== “loading”) {
callback();
} else {
document.addEventListener(“DOMContentLoaded”, callback);
}
})(() => {
window.TastyRecipes.cookMode.init();
});
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 );
});



Leave a Comment