IT |
InfoQ |
Article: Debugging Production: eBPF Chaos |
https://www.infoq.com/articles/debugging-production-ebpf-chaos/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global
|
Article Debugging Production eBPF ChaosThis article shares insights into learning eBPF as a new cloud native technology which aims to improve Observability and Security workflows You ll learn how chaos engineering can help and get an insight into eBPF based observability and security use cases Breaking them in a professional way also inspires new ideas for chaos engineering itself By Michael Friedrich |
2023-06-20 09:05:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] 企業が求めるエンジニア言語ランキング 2位「R」、3位「Go」 1位は? 企業DB運営会社が発表 |
https://www.itmedia.co.jp/news/articles/2306/20/news183.html
|
itmedia |
2023-06-20 18:52:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia Mobile] マイナポイントが別人に付与される事案は計172件 ログアウト漏れや決済サービスIDの誤入力などが原因 |
https://www.itmedia.co.jp/mobile/articles/2306/20/news179.html
|
itmediamobile |
2023-06-20 18:30:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia Mobile] 「OCN モバイル ONE」「OCN 光」「050 plus」などの新規受付停止へ |
https://www.itmedia.co.jp/mobile/articles/2306/20/news177.html
|
itmediamobile |
2023-06-20 18:17:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia Mobile] エクシモ、イルモ──ドコモの新プラン名、続々とトレンド入り 現行“ギガホ”より分かりづらい? “~モ”に賛否両論 |
https://www.itmedia.co.jp/mobile/articles/2306/20/news172.html
|
賛否両論 |
2023-06-20 18:06:00 |
TECH |
Techable(テッカブル) |
kintone連携のメール送信サービス「kMailer」、ChatGPT活用の新機能を追加 |
https://techable.jp/archives/211958
|
chatgpt |
2023-06-20 09:00:52 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
【AtCoder】競プロゴリ押し解法のノウハウ ~ 考察を投げ出したい ~ |
https://qiita.com/halcyonFX/items/33683fcd2f2f445fa39f
|
atcoder |
2023-06-20 18:56:45 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ChatGPT APIのFunction callingを使って頑張らずにチャットをアクションに繋げる |
https://qiita.com/ysv/items/cbdbb994dac790e26489
|
chatgptapi |
2023-06-20 18:50:09 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
東京の気温を現実の7セグで表示するWEBAppをGPT-4と作る |
https://qiita.com/T-Oda-BTO/items/9eaa449083883b6a4b0d
|
webapp |
2023-06-20 18:13:13 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
テストの責任範囲考えてる?【Ruby/Rails Minitest】 |
https://qiita.com/Terao-Takumi/items/9d8f543f0ac16a27fc10
|
classsav |
2023-06-20 18:42:31 |
Linux |
Ubuntuタグが付けられた新着投稿 - Qiita |
VS Code Server for WSL closed unexpectedlyの対処 |
https://qiita.com/am9/items/05f9e52b72d5d1c01095
|
forwslclosedunexpectedly |
2023-06-20 18:16:57 |
golang |
Goタグが付けられた新着投稿 - Qiita |
Go言語 基本文法 ~vol.1 基礎編~ |
https://qiita.com/nao_United92/items/78c0926fee7dd40ba161
|
言語 |
2023-06-20 18:59:46 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
テストの責任範囲考えてる?【Ruby/Rails Minitest】 |
https://qiita.com/Terao-Takumi/items/9d8f543f0ac16a27fc10
|
classsav |
2023-06-20 18:42:31 |
技術ブログ |
Mercari Engineering Blog |
非エンジニアのためのデータ集計環境について |
https://engineering.mercari.com/blog/entry/20230619-1b2e1f1d50/
|
hellip |
2023-06-20 10:00:43 |
技術ブログ |
Developers.IO |
Cloudinary の新しい変換生成ツール Transformation Builder が利用可能になりました |
https://dev.classmethod.jp/articles/cloudinary-transformation-builder-is-now-available/
|
cloudinary |
2023-06-20 09:21:09 |
海外TECH |
DEV Community |
Learn serverless on AWS step-by-step - SQS |
https://dev.to/kumo/learn-serverless-on-aws-step-by-step-sqs-26c8
|
Learn serverless on AWS step by step SQS TL DRIn this series I try to explain the basics of serverless on AWS to enable you to build your own serverless applications With last article we discovered how to use EventBridge to build event driven applications Today we will dive deeper into events management by taking a look at SQS and its integration with lambda functions IntroductionSQS is Amazon s Simple Queue Service As its name suggests it is a fully managed queue service that allows you to store messages while waiting for them to be processed It is a very useful service to decouple your applications and to build event driven applications It is also a very good way to handle asynchronous tasks and to manage your application s load In this article we will use SQS to find a solution to a problem imagine you have an external API that only allows connection at a time for example to avoid spamming How do you prevent it to be overwhelmed by your users but still make sure that every user request will be eventually processed This is where SQS comes in handy One of SQS use cases is to store messages and limit the throughput of your application If a lambda function processes your messages you can limit the number of concurrent executions of this function here we would set it to and this Lambda function will process all the messages stored in the queue by Resumed in a small schema it would look like this What are we going to build Based on this use case let s build a fake ordering app where a constraint is that only order can be processed at a time We will use SQS to store the orders and a lambda function to process them Using this method there is a possibility that a user has to wait several minutes before his order is processed to fix this we will publish an event with EventBridge when the order is processed and the user will be notified by an email using SES when his order is ready The app should look like this once we are done Creating the SQS queue and its target Lambda functionAs always you are going to use AWS CDK combined with TypeScript to provision this application If you need a refresher you can check the first article of this series where I go deeper into the setup of the project Let s start by the core of our application the SQS queue and the lambda function that will process the orders import as cdk from aws cdk lib import Construct from constructs import path from path export class LearnServerlessStack extends cdk Stack constructor scope Construct id string props cdk StackProps super scope id props create a FIFO SQS queue const ordersQueue new cdk aws sqs Queue this ordersQueue visibilityTimeout cdk Duration seconds fifo true defined an event source for the queue with a batch size of const eventSource new cdk aws lambda event sources SqsEventSource ordersQueue batchSize create a Lambda function that will process the orders bind it to the event source const executeOrder new cdk aws lambda nodejs NodejsFunction this executeOrder entry path join dirname executeOrder handler ts handler handler reservedConcurrentExecutions timeout cdk Duration seconds executeOrder addEventSource eventSource With this code snippet you will provision a SQS Queue and a Lambda function Every message sent to the queue will trigger the lambda function and the lambda function will process the messages by because of the concurrency execution at a time and the batch size each message is composed of order I set a timeout of seconds for the lambda function for demo purposes I want the fake processing to be very long and the visibility timeout to seconds AWS recommends to set the visibility timeout to times the timeout of your lambda function so that the message is not processed twice if the lambda function fails It s a tricky topic learn more here Provision the rest of the infrastructure Non lambda resourcesAs seen on the introduction schema we also need to provision an event bus an API gateway and a SES Identity Let s do it import orderExecutedHtmlTemplate from orderExecutedHtmlTemplate previous code Provision a rest APIconst restApi new cdk aws apigateway RestApi this restApi Provision an event bus and a rule to trigger the notification Lambda functionconst ordersEventBus new cdk aws events EventBus this ordersEventBus const notifyOrderExecutedRule new cdk aws events Rule this notifyOrderExecutedRule eventBus ordersEventBus eventPattern source notifyOrderExecuted detailType orderExecuted Provision a SES template to send beautiful emailsconst orderExecutedTemplate new cdk aws ses CfnTemplate this orderExecutedTemplate template htmlPart orderExecutedHtmlTemplate subjectPart Your order was passed to our provider templateName orderExecutedTemplate This part is common to my SES article No need to follow it if you already have a SES Identityconst DOMAIN NAME pchol fr const hostedZone new cdk aws route HostedZone this hostedZone zoneName DOMAIN NAME const identity new cdk aws ses EmailIdentity this sesIdentity identity cdk aws ses Identity publicHostedZone hostedZone In this snippet I create all the necessary resources this is based on previous articles if you need a refresher on API Gateway EventBridge or SES you can check them out I used a simple HTML template to send the email exported from a ts file it contains the variables itemName quantity and username that will be replaced by the values of the order export const orderExecutedHtmlTemplate lt html gt lt head gt lt style gt font family sans serif text align center padding margin title color fff background bb padding em container border px solid bb border radius em margin em auto max width px overflow hidden message padding em line height em color c footer font size em color lt style gt lt head gt lt body gt lt div class container gt lt div class title gt lt h gt Hello username lt h gt lt div gt lt div class message gt lt p gt Your order of quantity itemName was passed to our provider lt p gt lt div gt lt div gt lt p class footer gt This is an automated message please do not try to answer lt p gt lt body gt lt html gt Lambda functions and interactionsTo end the provisioning part of this article let s create the two missing lambda functions and the interfaces between theme and the other resources previous code Create the request order lambda functionconst requestOrder new cdk aws lambda nodejs NodejsFunction this requestOrder entry path join dirname requestOrder handler ts handler handler environment QUEUE URL ordersQueue queueUrl Grant the lambda function the right to send messages to the SQS queue add API Gateway as a triggerordersQueue grantSendMessages requestOrder restApi root addResource request order addMethod POST new cdk aws apigateway LambdaIntegration requestOrder const executeOrder new cdk aws lambda nodejs NodejsFunction this executeOrder entry path join dirname executeOrder handler ts handler handler environment EVENT BUS NAME ordersEventBus eventBusName NEW Add EVENT BUS NAME to the environment variables of the executeOrder lambda function reservedConcurrentExecutions timeout cdk Duration seconds executeOrder addEventSource eventSource NEW grant the lambda function the right to put events to the event busexecuteOrder addToRolePolicy new cdk aws iam PolicyStatement actions events PutEvents resources ordersEventBus eventBusArn Create the notifyOrderExecuted lambda functionconst notifyOrderExecuted new cdk aws lambda nodejs NodejsFunction this notifyOrderExecuted entry path join dirname notifyOrderExecuted handler ts handler handler environment SENDER EMAIL contact identity emailIdentityName TEMPLATE NAME orderExecutedTemplate ref Grant the lambda function the right to send emails add the lambda as a target of the event rulenotifyOrderExecuted addToRolePolicy new cdk aws iam PolicyStatement actions ses SendTemplatedEmail resources notifyOrderExecutedRule addTarget new cdk aws events targets LambdaFunction notifyOrderExecuted We are done with the provisioning part Let s move on to the most interesting part the code deployed inside the lambda functions Lambda functions deployed codeLet s start with the requestOrder lambda function This function is triggered by a POST HTTP request and will send a message to the SQS queue It will also return a HTTP status code to the client in case of success import SQSClient SendMessageCommand from aws sdk client sqs import v as uuidv from uuid const client new SQSClient export const handler async body body string Promise lt statusCode number body string gt gt const queueUrl process env QUEUE URL if queueUrl undefined throw new Error Missing environment variables const itemName quantity username userEmail JSON parse body as itemName string quantity number username string userEmail string if itemName undefined quantity undefined username undefined userEmail undefined return Promise resolve statusCode body JSON stringify message Missing required parameters await client send new SendMessageCommand QueueUrl queueUrl MessageBody JSON stringify itemName quantity username userEmail MessageGroupId ORDER REQUESTED MessageDeduplicationId uuidv return Promise resolve statusCode body JSON stringify message Order requested This snippet does the following things Usual parse the body of the POST request to get the values we needSend a message to the SQS queue with a unique ID to avoid duplicates and a constant group ID to ensure the order of the messages inside this groupReturn a HTTP status code to the clientNext lambda function executeOrder This function is triggered by the SQS queue so it will have a special typing as input It will fake a seconds connection with an external API and then send an event on the event bus import EventBridgeClient PutEventsCommand from aws sdk client eventbridge const client new EventBridgeClient export const handler async event Records body string Promise lt void gt gt const eventBusName process env EVENT BUS NAME if eventBusName undefined throw new Error Missing environment variables const body event Records console log Communication with external API started await new Promise resolve gt setTimeout resolve console log Communication with external API finished await client send new PutEventsCommand Entries EventBusName eventBusName Source notifyOrderExecuted DetailType orderExecuted Detail body This snippet does the following things New parse the SQS input The type is an array of records Because we set the batch size to we can assume that the array will always have a length of Wait for seconds to fake a connection with an external APISend an event on the event bus with the body of the SQS message as the detail Notice I set for this call the same source and detail type as the event rule target otherwise the target would not be triggeredFinal lambda function notifyOrderExecuted This function is triggered by the event bus so it will have another typing as input refresher here It will send an email to the user using a template stored in SES import SESvClient SendEmailCommand from aws sdk client sesv const client new SESvClient export const handler async event detail itemName string quantity number username string userEmail string Promise lt void gt gt const senderEmail process env SENDER EMAIL const templateName process env TEMPLATE NAME if senderEmail undefined templateName undefined throw new Error Missing environment variables const itemName quantity username userEmail event detail await client send new SendEmailCommand FromEmailAddress senderEmail Content Template TemplateName templateName TemplateData JSON stringify itemName quantity username Destination ToAddresses userEmail This snippet does the following things Parse the EventBridge input It was automatically parsed from string to object we just have to pick properties we need Send a templated email using SES Remember that the TemplateData must contain exactly the same keys as the template you created in SES otherwise the send will silently fail We are done with the code Let s finish this article by testing our app Testing our applicationFor this test I m going to make consecutive API calls to the request order endpoint If everything is alright I should receive an email after seconds and a second email after seconds because the executeOrder Lambda only processes one message at a time and sleeps for O seconds Here are the requests I made I ordered bananas and cookies I am very hungry Now let s check my emails I received the emails with the correct quantities Trust me when I say that I received the first email after seconds and the second one after seconds Homework We only built a minimalistic application and there are a lot of things we can improve Here are some ideas that you should definitely be able to try if you followed this series Add a database to store the orders and a GET endpoint to retrieve themOnly allow authenticated users to request ordersInteract with a real API to list the items and their pricesYou could also build a small front end interacting with this back end but I will cover this in a future article ConclusionThis tutorial was only a small practical example of what you can do with events and SQS on AWS SQS can be adapted to way more use cases and I encourage you to check the documentation to learn more about it I plan to continue this series of articles on a bi monthly basis I already covered the creation of simple lambda functions and REST APIs as well as interacting with DynamoDB databases and S buckets You can follow this progress on my repository I will cover new topics like front end deployment type safety more advanced patterns and more If you have any suggestions do not hesitate to contact me I would really appreciate if you could react and share this article with your friends and colleagues It will help me a lot to grow my audience Also don t forget to subscribe to be updated when the next article comes out I you want to stay in touch here is my twitter account I often post or re post interesting stuff about AWS and serverless feel free to follow me |
2023-06-20 09:30:46 |
海外TECH |
DEV Community |
What's your Lucky CSS Pattern? Check It Now! |
https://dev.to/afif/whats-your-lucky-css-pattern-check-it-now-1g18
|
What x s your Lucky CSS Pattern Check It Now You liked my CSS Patterns collection but you are lost and you don t know which one to choose Don t worry I have the solution for you One click and you have the best CSS Pattern that matches your preference Get Your CSS Pattern I have developed an advanced AI better than ChatGPT that will read your mind scan your actual mood find out the web projects you are working on check your bank account then it will select THE CSS Pattern you want with the perfect colors What are you waiting for Get your CSS Pattern now Yes you already guess it I will simply generate a random pattern from my collection but I need to make the article a bit lengthy and it s trending to talk about AI In addition to the pattern you can easily adjust the colors the size and get the code with one click You can reload the page to generate a new one BUT the first pattern you get is your Lucky CSS Pattern Share yours in the comments section A CSS Pattern can tell a lot about its owner I created unique CSS patterns The best collection Temani Afif・May ・ min read showdev webdev css codepen I made CSS loaders for your next project Temani Afif・May ・ min read css webdev beginners html underline overlay animations The ultimate CSS collection Temani Afif・Mar ・ min read css beginners webdev codepen |
2023-06-20 09:17:34 |
海外TECH |
DEV Community |
AI will NOT replace front-end developers! |
https://dev.to/kristiyan_velkov/ai-will-not-replace-front-end-developers-21eh
|
AI will NOT replace front end developers IntroductionAI or Artificial Intelligence refers to the simulation of human intelligence in machines that are programmed to perform tasks that typically require human intelligence AI systems are designed to perceive their environment reason and learn from the available data and make decisions or take actions to achieve specific goals While AI and automation can enhance certain aspects of front end development they cannot completely replace the role of front end developers Front end development involves a combination of technical skills creativity problem solving and user centric thinking that requires human expertise AI technologies may assist with tasks like code generation automated testing or performance optimization BUT the critical thinking decision making and adaptability of human developers are irreplaceable Reasons why AI will not replace front end developers Creativity Front end development requires creative thinking to design visually appealing and user friendly interfaces AI lacks the creative intuition and artistic sense that human developers possess User Experience Front end developers focus on creating seamless and intuitive user experiences This involves understanding user needs behavior and emotions which requires empathy and human judgment Problem solving Front end developers are skilled problem solvers who can analyze complex requirements find optimal solutions and address user experience challenges AI while capable of automating certain tasks cannot replicate the comprehensive problem solving abilities of human developers Adaptability Front end development often involves adapting to changing technologies design trends and user expectations Human developers can quickly learn and adopt new tools frameworks and techniques while AI systems require human intervention to update and adapt Collaboration Front end developers work closely with designers back end developers and stakeholders to bring a project to life Effective communication teamwork and understanding of multiple perspectives are vital which AI cannot replicate Contextual Decision making Front end developers make design and implementation decisions based on contextual factors such as the target audience business goals and branding requirements AI lacks the contextual understanding necessary for making informed decisions Continuous Learning Front end developers constantly learn and improve their skills to keep up with the evolving web development landscape They stay updated on new technologies best practices and emerging trends AI systems while capable of learning rely on human input and training data Quality Assurance Front end developers ensure the quality and performance of web applications through testing debugging and optimization Their critical thinking and attention to detail are essential in delivering high quality user experiences Human Touch Front end development involves creating experiences that resonate with human users The human touch empathy and understanding of human psychology are essential elements that AI cannot replicate Future proofing Front end developers possess the adaptability and problem solving skills to navigate the ever changing landscape of technology They can envision future user needs and anticipate trends ensuring that applications remain relevant and innovative In summary AI can be a valuable tool for front end developers but it cannot replace the expertise creativity and human touch that they bring to the table The collaboration between AI and front end developers has the potential to result in more efficient and innovative solutions in the field of web development If you like my work and want to support me to work hard please donate via Revolut website payment or use the QR code above Thanks a bunch for supporting me It means a LOT |
2023-06-20 09:08:00 |
海外TECH |
DEV Community |
How to Build a Fancy Testimonial Slider with Tailwind CSS and Vue |
https://dev.to/cruip_com/how-to-build-a-fancy-testimonial-slider-with-tailwind-css-and-vue-32bb
|
How to Build a Fancy Testimonial Slider with Tailwind CSS and Vue Live Demo Download Welcome to the third and final part of our series on How to Build a Fancy Testimonial Slider with Tailwind CSS This post will guide you through the development of a Vue and Tailwind CSS based fancy testimonial slider featuring comprehensive TypeScript compatibility As usual to get a better idea of how the final outcome will look check out the live demo or one of our beautiful Tailwind CSS templates e g Stellar a dark landing page template based on Next js Let s get started with the tutorial You can keep your favorite code editor open while you follow along Create the structure for the Vue componentTo kick things off let s create a new file called FancyTestimonialsSlider vue for our component and add the following code lt script setup lang ts gt import ref from vue import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg const active ref lt number gt const autorotate ref lt boolean gt true const autorotateTiming ref lt number gt interface Testimonial img string quote string name string role string const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to be able to select between formats ture responses is a game changer name Jessie J role Ltd Head of Product img TestimonialImg quote I have been using this product for a few weeks now and I am blown away by the results My skin looks visibly brighter and smoother and I have received so many compliments on my complexion name Mark Luk role Spark Founder amp CEO img TestimonialImg quote As a busy professional I don t have a lot of time to devote to working out But with this fitness program I have seen amazing results in just a few short weeks The workouts are efficient and effective name Jeff Kahl role Appy Product Lead lt script gt lt template gt lt div class w full max w xl mx auto text center gt lt gt lt div gt lt template gt Firstly note that we are using the new syntax setup of Vue which allows us to use the Composition API inside the script tag without needing to use the export default syntax Next we have imported the testimonials images and defined the variables active autorotate and autorotateTiming which we have already used in the previous HTML and React components To ensure reactivity for these variables we have used the ref functionfrom Vue s Composition API This allows us to treat the variables as reactive without using the data object Additionally we ve defined the testimonials array that contains the properties for each testimonial including the image quote name and role Lastly since we are adopting TypeScript we ve defined the Testimonial interface to specify the type of each testimonial property Great Now let s move on to constructing the HTML structure of our component within the template tag lt template gt lt div class w full max w xl mx auto text center gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt template key index v for testimonial in testimonials gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt template gt lt div gt lt div gt lt div gt lt Text gt lt div class mb transition all duration delay ease in out gt lt div class relative flex flex col gt lt template key index v for testimonial in testimonials gt lt div class text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt template gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt template key index v for testimonial index in testimonials gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration class active index bg indigo text white shadow indigo bg white hover bg indigo text slate click active index gt lt span gt testimonial name lt span gt lt span class active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt template gt lt div gt lt div gt lt template gt While in React we emploied the map method to iterate over the testimonials array in Vue we have used a template tag with the v for attribute to render each testimonial To add dynamic behavior to the buttons we ve used the class directive This allows us to apply different classes to the buttons based on whether they represent the active testimonial or not The active state is denoted by the classes bg indigo text white shadow indigo while the inactive state uses the classes bg white hover bg indigo text slate To handle user interaction we ve added an click event to each button which updates the active testimonial index We re making solid progress but we still need to show only the active testimonial and define the fancy transitions which are a visually appealing feature of this component Show only the active testimonial and define transitionsWe will accomplish these two tasks in a single step by using a transition component We ll use the Headless UI library instead of Vue s built in Transition component If you ve followed our previous tutorial on creating a video modal component you might already be familiar with this preference Let s start by installing Headless UI using the command npm install headlessui react latest Once installed we can import the TransitionRoot component and wrap the image and text of the active testimonial within it lt script setup lang ts gt import ref from vue import TransitionRoot from headlessui vue import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg const active ref lt number gt const autorotate ref lt boolean gt true const autorotateTiming ref lt number gt interface Testimonial img string quote string name string role string const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to be able to select between formats ture responses is a game changer name Jessie J role Ltd Head of Product img TestimonialImg quote I have been using this product for a few weeks now and I am blown away by the results My skin looks visibly brighter and smoother and I have received so many compliments on my complexion name Mark Luk role Spark Founder amp CEO img TestimonialImg quote As a busy professional I don t have a lot of time to devote to working out But with this fitness program I have seen amazing results in just a few short weeks The workouts are efficient and effective name Jeff Kahl role Appy Product Lead lt script gt lt template gt lt div class w full max w xl mx auto text center gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt template key index v for testimonial index in testimonials gt lt TransitionRoot show active index class absolute inset h full z enter transition ease cubic bezier duration order first enterFrom opacity rotate deg enterTo opacity rotate leave transition ease cubic bezier duration leaveFrom opacity rotate leaveTo opacity rotate deg gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt TransitionRoot gt lt template gt lt div gt lt div gt lt div gt lt Text gt lt div class mb transition all duration delay ease in out gt lt div class relative flex flex col ref testimonialsRef gt lt template key index v for testimonial index in testimonials gt lt TransitionRoot show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x gt lt div class text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt TransitionRoot gt lt template gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt template key index v for testimonial index in testimonials gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration class active index bg indigo text white shadow indigo bg white hover bg indigo text slate click active index gt lt span gt testimonial name lt span gt lt span class active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt template gt lt div gt lt div gt lt template gt By using the show directive we can control which testimonial is currently displayed while hiding the others We ve also applied Tailwind CSS classes to define entrance and exit animations As a result when transitioning between testimonials the text will gracefully fade in from the left and the image will fade in with a clockwise rotation Improving UX during transitionsNow let s make sure to provide an optimal user experience As we have seen before if one testimonial has more text than the others the height of the testimonial will abruptly change during the transition resulting in a less pleasant effect To prevent this from happening we will add a method called heightFix to our component which calculates the height of the current testimonial and applies it to the parent element const heightFix gt setTimeout gt if testimonialsRef value amp amp testimonialsRef value parentElement testimonialsRef value parentElement style height testimonialsRef value clientHeight px The heightFix method is fired when the before enter event emitted by the transition component just like this lt template key index v for testimonial index in testimonials gt lt TransitionRoot show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x before enter heightFix gt lt div class text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt TransitionRoot gt lt template gt Enabling autorotate functionality on component mountNow let s add a final touch to our testimonial slider by enabling automatic rotation between testimonials We want them to automatically rotate ewith a second interval To do this we will use Vue s onMounted hook which allows us to execute code when the component is mounted let interval number onMounted gt if autorotate value return interval setInterval gt active value active value testimonials length active value autorotateTiming value We also need to ensure that the interval is cleared when the component is unmounted We we will use the onUnmounted hook for that onUnmounted gt clearInterval interval Finally we want to turn off the automatic rotation when the user interacts with the buttons We ll create a method called stopAutorotate for this purpose This method changes the autorotate variable from true to false and clears the interval const stopAutorotate gt autorotate value false clearInterval interval To activate this method we ll simply call it when a user clicks on one of the buttons click active index stopAutorotate Et voilà We have created an advanced testimonial component that provides an optimal user experience and visually appealing animations But there is still something we can do to improve it Currently using the component requires defining the testimonial properties directly within the component itself limiting its flexibility That s why we want to make our component reusable Making the testimonial component reusableHere s the plan we ll transfer the testimonials array to the parent component which in this case is FancyTestimonialSliderPage vue Then we will pass the array to the component through the testimonials prop lt script setup lang ts gt import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg import TestimonialImg from assets testimonial jpg import FancyTestimonialsSlider from components FancyTestimonialsSlider vue const testimonials img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to be able to select between formats ture responses is a game changer name Jessie J role Ltd Head of Product img TestimonialImg quote I have been using this product for a few weeks now and I am blown away by the results My skin looks visibly brighter and smoother and I have received so many compliments on my complexion name Mark Luk role Spark Founder amp CEO img TestimonialImg quote As a busy professional I don t have a lot of time to devote to working out But with this fitness program I have seen amazing results in just a few short weeks The workouts are efficient and effective name Jeff Kahl role Appy Product Lead lt script gt lt template gt lt FancyTestimonialsSlider testimonials testimonials gt lt template gt Of course we will also need to modify the component we have created so that it can receive testimonial data from the outside To do this we will use the defineProps function of Vue which allows us to define the props of a component as follows const props defineProps lt testimonials Testimonial gt const testimonials props testimonialsFinally now that our testimonials are defined in the parent component we can safely remove the image imports in our testimonial component We no longer need them since the parent component takes care of that And here we have our reusable testimonial component lt script setup lang ts gt import ref onMounted onUnmounted from vue import TransitionRoot from headlessui vue const testimonialsRef ref lt HTMLCanvasElement null gt null const active ref lt number gt const autorotate ref lt boolean gt true const autorotateTiming ref lt number gt let interval number interface Testimonial img string quote string name string role string const props defineProps lt testimonials Testimonial gt const testimonials props testimonials const heightFix gt setTimeout gt if testimonialsRef value amp amp testimonialsRef value parentElement testimonialsRef value parentElement style height testimonialsRef value clientHeight px const stopAutorotate gt autorotate value false clearInterval interval onMounted gt if autorotate value return interval setInterval gt active value active value testimonials length active value autorotateTiming value onUnmounted gt clearInterval interval lt script gt lt template gt lt div class w full max w xl mx auto text center gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt template key index v for testimonial index in testimonials gt lt TransitionRoot show active index class absolute inset h full z enter transition ease cubic bezier duration order first enterFrom opacity rotate deg enterTo opacity rotate leave transition ease cubic bezier duration leaveFrom opacity rotate leaveTo opacity rotate deg gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt TransitionRoot gt lt template gt lt div gt lt div gt lt div gt lt Text gt lt div class mb transition all duration delay ease in out gt lt div class relative flex flex col ref testimonialsRef gt lt template key index v for testimonial index in testimonials gt lt TransitionRoot show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x before enter heightFix gt lt div class text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt TransitionRoot gt lt template gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt template key index v for testimonial index in testimonials gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration class active index bg indigo text white shadow indigo bg white hover bg indigo text slate click active index stopAutorotate gt lt span gt testimonial name lt span gt lt span class active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt template gt lt div gt lt div gt lt template gt And there you have it We have reached the end of this tutorial and our mini series on creating a fancy testimonial slider with Tailwind CSS If you found this post helpful don t miss out on the previous parts covering Alpine js and Next js Additionally feel free to explore our Tailwind CSS tutorials section where we showcase remarkable components and effects that seamlessly complement your projects |
2023-06-20 09:01:25 |
海外TECH |
DEV Community |
How to Build a Fancy Testimonial Slider with Tailwind CSS and Next.js |
https://dev.to/cruip_com/how-to-build-a-fancy-testimonial-slider-with-tailwind-css-and-nextjs-3bel
|
How to Build a Fancy Testimonial Slider with Tailwind CSS and Next js Live Demo Download Welcome to the second part of the series of How to Build a Fancy Testimonial Slider with Tailwind CSS In the previous tutorial we learned how to create a testimonial slider using Alpine js Now get ready to take your skills to the next level as we will build a powerful Next js component that achieves the same stunning result The significance of customer testimonials in driving your visitors purchasing decisions for your product or service is widely acknowledged and understood so if you want to have a look at how we previously developed this component for our templates we recommend checking out our Dark Next js landing page template called Stellar Let s get started Creating the componentBut enough talking let s start by creating a file fancy testimonial slider tsx for our component use client import useState from react import Image StaticImageData from next image import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg interface Testimonial img StaticImageData quote string name string role string export default function FancyTestimonialsSlider const active setActive useState lt number gt const autorotate setAutorotate useState lt boolean gt true const autorotateTiming number const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img TestimonialImg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img TestimonialImg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI return lt div className w full max w xl mx auto text center gt lt div gt As usual we have declared use client at the very top of the file to indicate that the component will be executed on the client side Additionally we have created three state variables that are needed to control the slider active to keep track of the active testimonial autorotate to enable or disable automatic rotation autorotateTiming to set the time for automatic rotationNext we ve defined an array of testimonials with their respective properties Leveraging TypeScript we ve also introduced the Testimonial interface to specify the type of each array element Now inside the component we can start building the HTML structure use client import useState from react import Image StaticImageData from next image import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg interface Testimonial img StaticImageData quote string name string role string export default function FancyTestimonialsSlider const active setActive useState lt number gt const autorotate setAutorotate useState lt boolean gt true const autorotateTiming number const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img TestimonialImg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img TestimonialImg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI return lt div className w full max w xl mx auto text center gt Testimonial image lt div className relative h gt lt div className absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div className h mask image linear gradient deg transparent theme colors white theme colors white gt testimonials map testimonial index gt lt Image key index className relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt div gt lt div gt lt div gt Text lt div className mb transition all duration delay ease in out gt lt div className relative flex flex col gt testimonials map testimonial index gt lt div key index className text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt div gt lt div gt Buttons lt div className flex flex wrap justify center m gt testimonials map testimonial index gt lt button key index className inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration active index bg indigo text white shadow indigo bg white hover bg indigo text slate onClick gt setActive index gt lt span gt testimonial name lt span gt lt span className active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt div gt lt div gt As you can see we have used the map method to iterate over the array of testimonials and dynamically generate the corresponding HTML elements For each testimonial we ve created an Image element to display the associated image a div to present the text and a button for the button In addition we implemented the onClick handler to update the active testimonial index when a button is clicked However the component is not yet functional as it renders all the images and text for each testimonial Instead we want to display only the active testimonial and introduce smooth transitions when switching between testimonials Managing the active testimonial and adding transitionsAs we did with the modal video component created in a previous tutorial we will use the Headless UI library for managing transitions So if we haven t already we need to install the library using the command npm install headlessui react latest Once the library is installed make sure to import the Transition component and wrap both the image and text of our testimonial within it Also don t forget to include the key index property within the Transition component use client import useState from react import Image StaticImageData from next image import Transition from headlessui react import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg interface Testimonial img StaticImageData quote string name string role string export default function FancyTestimonialsSlider const active setActive useState lt number gt const autorotate setAutorotate useState lt boolean gt true const autorotateTiming number const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img TestimonialImg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img TestimonialImg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI return lt div className w full max w xl mx auto text center gt Testimonial image lt div className relative h gt lt div className absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div className h mask image linear gradient deg transparent theme colors white theme colors white gt testimonials map testimonial index gt lt Transition key index show active index className absolute inset h full z enter transition ease cubic bezier duration order first enterFrom opacity rotate deg enterTo opacity rotate leave transition ease cubic bezier duration leaveFrom opacity rotate leaveTo opacity rotate deg gt lt Image className relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt Transition gt lt div gt lt div gt lt div gt Text lt div className mb transition all duration delay ease in out gt lt div className relative flex flex col gt testimonials map testimonial index gt lt Transition key index show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x gt lt div className text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt Transition gt lt div gt lt div gt Buttons lt div className flex flex wrap justify center m gt testimonials map testimonial index gt lt button key index className inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration active index bg indigo text white shadow indigo bg white hover bg indigo text slate onClick gt setActive index gt lt span gt testimonial name lt span gt lt span className active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt div gt lt div gt Improving transitions between testimonials with varying heightsAt this point to enhance the user experience when transitioning between testimonials with different heights we will create a method called heightFix This method calculates the height of the current testimonial and applies it to the container element By incorporating the classes transition all duration delay ease in out to the container element the height will transition smoothly when switching between testimonials of varying heights To accomplish this we first need to reference the element for which we want to calculate the height using the ref testimonialsRef attribute Next we will define the heightFix method const heightFix gt if testimonialsRef current amp amp testimonialsRef current parentElement testimonialsRef current parentElement style height testimonialsRef current clientHeight px This method should be triggered in two situations on component mount using the useEffect hook and whenever there is a transition between testimonials utilizing the beforeEnter callback provided by the Transition component use client import useState useRef useEffect from react import Image StaticImageData from next image import Transition from headlessui react import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg interface Testimonial img StaticImageData quote string name string role string export default function FancyTestimonialsSlider const testimonialsRef useRef lt HTMLDivElement gt null const active setActive useState lt number gt const autorotate setAutorotate useState lt boolean gt true const autorotateTiming number const testimonials Testimonial img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img TestimonialImg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img TestimonialImg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI const heightFix gt if testimonialsRef current amp amp testimonialsRef current parentElement testimonialsRef current parentElement style height testimonialsRef current clientHeight px useEffect gt heightFix return lt div className w full max w xl mx auto text center gt Testimonial image lt div className relative h gt lt div className absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div className h mask image linear gradient deg transparent theme colors white theme colors white gt testimonials map testimonial index gt lt Transition key index show active index className absolute inset h full z enter transition ease cubic bezier duration order first enterFrom opacity rotate deg enterTo opacity rotate leave transition ease cubic bezier duration leaveFrom opacity rotate leaveTo opacity rotate deg gt lt Image className relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt Transition gt lt div gt lt div gt lt div gt Text lt div className mb transition all duration delay ease in out gt lt div className relative flex flex col ref testimonialsRef gt testimonials map testimonial index gt lt Transition key index show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x beforeEnter gt heightFix gt lt div className text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt Transition gt lt div gt lt div gt Buttons lt div className flex flex wrap justify center m gt testimonials map testimonial index gt lt button key index className inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration active index bg indigo text white shadow indigo bg white hover bg indigo text slate onClick gt setActive index gt lt span gt testimonial name lt span gt lt span className active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt div gt lt div gt Adding the auto rotate featureThe final step of the tutorial is to add the auto rotate functionality Additionally to ensure an optimal user experience we want to disable auto rotation when the user interacts with the buttons As you may have already noticed we defined the autorotate and autorotateTiming variables from the beginning The autorotate variable determines whether auto rotation is active or not while the autorotateTiming variable sets the time interval between each slide To activate the auto rotate feature we can simply add a useEffect hook that triggers whenever there are changes in the active or autorotate state variables useEffect gt if autorotate return const interval setInterval gt setActive active testimonials length active gt active autorotateTiming return gt clearInterval interval active autorotate Finally to disable auto rotation when the user interacts with the buttons we can simply set the autorotate state variable to false on the onClick event lt button key index className inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration active index bg indigo text white shadow indigo bg white hover bg indigo text slate onClick gt setActive index setAutorotate false gt lt span gt testimonial name lt span gt lt span className active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt The component is now complete However it is currently not reusable because we have defined the content of the testimonials within the component itself To make the component reusable some modifications are necessary Let s see what needs to be done Create a reusable testimonials componentTo make the component reusable we need to move the testimonials content to the parent component in our case the page tsx file Then we will pass the testimonials array as a prop to the FancyTestimonialsSlider component export const metadata title Fancy Testimonials Slider Cruip Tutorials description Page description import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import TestimonialImg from public testimonial jpg import FancyTestimonialsSlider from components fancy testimonials slider export default function FancyTestimonialSliderPage const testimonials img TestimonialImg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img TestimonialImg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img TestimonialImg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI return lt FancyTestimonialsSlider testimonials testimonials gt We also need to update the FancyTestimonialsSlider component to accept props To do this the previously defined function as FancyTestimonialsSlider will change to FancyTestimonialsSlider testimonials testimonials Testimonial Finally we can remove the imported images from the FancyTestimonialsSlider component since they will be passed as props Here is the updated complete component use client import useState useRef useEffect from react import Image StaticImageData from next image import Transition from headlessui react interface Testimonial img StaticImageData quote string name string role string export default function FancyTestimonialsSlider testimonials testimonials Testimonial const testimonialsRef useRef lt HTMLDivElement gt null const active setActive useState lt number gt const autorotate setAutorotate useState lt boolean gt true const autorotateTiming number useEffect gt if autorotate return const interval setInterval gt setActive active testimonials length active gt active autorotateTiming return gt clearInterval interval active autorotate const heightFix gt if testimonialsRef current amp amp testimonialsRef current parentElement testimonialsRef current parentElement style height testimonialsRef current clientHeight px useEffect gt heightFix return lt div className w full max w xl mx auto text center gt Testimonial image lt div className relative h gt lt div className absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div className h mask image linear gradient deg transparent theme colors white theme colors white gt testimonials map testimonial index gt lt Transition key index show active index className absolute inset h full z enter transition ease cubic bezier duration order first enterFrom opacity rotate deg enterTo opacity rotate leave transition ease cubic bezier duration leaveFrom opacity rotate leaveTo opacity rotate deg gt lt Image className relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt Transition gt lt div gt lt div gt lt div gt Text lt div className mb transition all duration delay ease in out gt lt div className relative flex flex col ref testimonialsRef gt testimonials map testimonial index gt lt Transition key index show active index enter transition ease in out duration delay order first enterFrom opacity translate x enterTo opacity translate x leave transition ease out duration delay absolute leaveFrom opacity translate x leaveTo opacity translate x beforeEnter gt heightFix gt lt div className text xl font bold text slate before content C after content D gt testimonial quote lt div gt lt Transition gt lt div gt lt div gt Buttons lt div className flex flex wrap justify center m gt testimonials map testimonial index gt lt button key index className inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration active index bg indigo text white shadow indigo bg white hover bg indigo text slate onClick gt setActive index setAutorotate false gt lt span gt testimonial name lt span gt lt span className active index text indigo text slate gt lt span gt lt span gt testimonial role lt span gt lt button gt lt div gt lt div gt We hope you enjoyed this tutorial and learned a thing or two about how simple it is to create enjoyable modern components to enrich your Tailwind CSS landing pages If you re interested in seeing how we developed the same testimonial slider for Alpine js and Vue check out the other two parts below |
2023-06-20 09:01:20 |
海外TECH |
DEV Community |
How to Build a Fancy Testimonial Slider with Tailwind CSS and Alpine.js |
https://dev.to/cruip_com/how-to-build-a-fancy-testimonial-slider-with-tailwind-css-and-alpinejs-3f0a
|
How to Build a Fancy Testimonial Slider with Tailwind CSS and Alpine js Live Demo Download Having testimonials on your landing page or website can be an excellent way to gain credibility and trust from potential customers So in this tutorial we will walk you through creating a fancy testimonial slider with Tailwind CSS and similar to the previous tutorials we will divide the guide into three parts using Alpine js Next js and Vue We ve created testimonial components for several of our Tailwind CSS templates but if you want to see in action the exact same slider component that we ll be creating in this tutorial we recommend taking a look at the Dark Next js landing page template called Stellar To begin we ll create the component in pure HTML utilizing the powerful combination of Tailwind CSS and the Alpine js library As usual we ll begin by setting up a basic HTML structure to house our component lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset utf gt lt title gt Fancy Testimonials Slider lt title gt lt meta name viewport content width device width initial scale gt lt link rel preconnect href gt lt link rel preconnect href crossorigin gt lt link href wght amp display swap rel stylesheet gt lt script src gt lt script gt lt script defer src x x dist cdn min js gt lt script gt lt script gt tailwind config theme extend fontFamily inter Inter sans serif lt script gt lt head gt lt body class relative font inter antialiased gt lt main class relative min h screen flex flex col justify center bg slate overflow hidden gt lt div class w full max w xl mx auto px md px py gt lt div class flex justify center gt lt Fancy testimonial slider gt lt div gt lt div gt lt main gt lt body gt lt html gt We ll start by designing a single testimonial and then we ll use the x for directive to iterate through all the testimonials defined ina a JavaScript array Creating the HTML structure of the testimonial with Tailwind CSSLet s set up HTML structure for our testimonial The content will consist of three parts Testimonial image Testimonial text Buttons for navigating between testimonials lt div class w full max w xl mx auto text center gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt div class absolute inset z gt lt img class relative top left translate x rounded full src testimonial jpg width height alt Testimonial gt lt div gt lt div gt lt div gt lt div gt lt Text gt lt div class mb gt lt div class relative flex flex col transition all duration delay ease in out gt lt div class text xl font bold text slate before content C after content D gt The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats lt div gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration bg indigo text white shadow indigo gt lt span gt Jessie J lt span gt lt span class text indigo gt lt span gt lt span gt Acme LTD lt span gt lt button gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration bg white hover bg indigo text slate gt lt span gt Nick V lt span gt lt span class text slate gt lt span gt lt span gt Malika Inc lt span gt lt button gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration bg white hover bg indigo text slate gt lt span gt Amelia W lt span gt lt span class text slate gt lt span gt lt span gt Panda AI lt span gt lt button gt lt div gt lt div gt Above the text we have created a circle with a diameter of px and applied a gradient to achieve a shading effect Next we have positioned the testimonial image within a container element with a height of px h To ensure that the testimonial avatar transitions along the circular shape without overlapping the underlying text we have applied a gradient mask to the container element To create the mask we have leveraged Tailwind CSS s arbitrary properties to define a custom class called mask image linear gradient deg transparent theme colors white theme colors white This class generates the CSS property mask image linear gradient deg transparent fff fff Great Now let s move on to the next part where we will use Alpine js s x for directive to generate multiple testimonials dynamically and use some Tailwind CSS classes to create transitions between testimonials Creating an x for loop to generate the testimonialsAs you may know everything in Alpine starts with the x data directive While in previous components it was sufficient to define a variable with an initial value in this case we need something more complex To maintain clean and organized code we ll use the global Alpine data and create a JavaScript object that contains all the necessary information to render our testimonials slider lt div class w full max w xl mx auto text center x data slider gt lt div gt lt Slider data and functionality gt lt script gt document addEventListener alpine init gt Alpine data slider gt active autorotate true autorotateTiming testimonials img testimonial jpg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img testimonial jpg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img testimonial jpg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI init if this autorotate this autorotateInterval setInterval gt this active this active this testimonials length this active this autorotateTiming lt script gt In the above code we have defined a component object called slider that contains the properties required by our slider which are active is an index that indicates which testimonial is currently displayed autorotate is a boolean that indicates whether the slider should rotate automatically or not autorotateTiming is a number that indicates the time interval in milliseconds at which the slider should rotate automatically testimonials is an array of objects that contains all the information needed to generate the various testimonials In addition we have defined an init method that runs when the component is initialized This method checks if the slider should rotate automatically and if so sets an interval that changes the active index every autorotateTiming milliseconds With the testimonials array now defined we can use the x for directive to iterate through the array and render the necessary elements for each testimonial This allows us to dynamically generate the testimonials on the page Let s proceed with the implementation of the x for directive lt div class w full max w xl mx auto text center x data slider gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt Alpine js template for testimonial images x for gt lt template x for testimonial index in testimonials key index gt lt div x show active index class absolute inset z gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt div gt lt template gt lt div gt lt div gt lt div gt lt Text gt lt div class mb gt lt div class relative flex flex col transition all duration delay ease in out gt lt Alpine js template for testimonials x for gt lt template x for testimonial index in testimonials key index gt lt div x show active index gt lt div class text xl font bold text slate before content C after content D x text testimonial quote gt lt div gt lt div gt lt template gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt Alpine js template for buttons x for gt lt template x for testimonial index in testimonials key index gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration class active index bg indigo text white shadow indigo bg white hover bg indigo text slate click active index gt lt span x text testimonial name gt lt span gt lt span class active index text indigo text slate gt lt span gt lt span x text testimonial role gt lt span gt lt button gt lt template gt lt div gt lt div gt We have effectively utilized the x for directive in three instances To generate the images for each testimonial To generate to dynamically generate the text content for each testimonial To generate the navigation buttons By adopting this approach we will be able to add or remove a testimonial from the array without having to change anything in the HTML This flexibility provides an efficient way to manage and update our code effortlessly Adding transitions between testimonialsTo make the slider more appealing let s add transitions between the testimonials To do this we will use the x transition directive in conjunction with Tailwind CSS classes Firstly we will add a degree rotation effect to the testimonial avatar with a custom easing effect lt div x show active index class absolute inset z x transition enter transition ease cubic bezier duration order first x transition enter start opacity rotate deg x transition enter end opacity rotate x transition leave transition ease cubic bezier duration x transition leave start opacity rotate x transition leave end opacity rotate deg gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt div gt For the testimonial text we will add a fading in out effect from left to right lt div x show active index x transition enter transition ease in out duration delay order first x transition enter start opacity translate x x transition enter end opacity translate x x transition leave transition ease out duration delay absolute x transition leave start opacity translate x x transition leave end opacity translate x gt lt div class text xl font bold text slate before content C after content D x text testimonial quote gt lt div gt lt div gt Final TouchesWe re nearly done with the testimonial component but there are a few final touches we can add to make it even better Disabling autorotation on user interactionOne important enhancement is to disable automatic rotation when the user interacts with the slider We can achieve this by adding a stopAutorotate method that clears the automatic rotation interval Let s implement it stopAutorotate clearInterval this autorotateInterval this autorotateInterval null And we call this method when the user interacts with the slider lt button class inline flex click active index stopAutorotate gt lt span x text testimonial name gt lt span gt lt span class active index text indigo text slate gt lt span gt lt span x text testimonial role gt lt span gt lt button gt This way the slider stops rotating automatically when the user clicks on one of the buttons But there s one last integration to be done Using CSS transitions between testimonials with different heightCurrently the text of each testimonial consists of a similar number of characters which results in all the testimonials having the same height However if one testimonial has significantly more text than the others the height of the slider abruptly changes producing an undesirable effect To mitigate this issue we have already added the classes transition all duration delay ease in out to the testimonial text wrapper However we also need to explicitly define the height of the testimonial text wrapper for the transition to take place For this we ll add a heightFix method that dynamically sets the height of the testimonial text wrapper based on the height of the current testimonial text which will be referenced by a x ref testimonials attribute heightFix this nextTick gt this refs testimonials style height this refs testimonials children this active offsetHeight px Then we ll invoke it both in the init method and within the watch magic property like this init if this autorotate this autorotateInterval setInterval gt this active this active this testimonials length this active this autorotateTiming this watch active callback gt this heightFix Essentially we are telling Alpine to call the heightFix method on page load and every time the active property changes Cool isn t it ConclusionsOur testimonial component is complete We can use it on any page of our website by simply copying the complete code and defining the testimonials array Here s the complete code lt Fancy testimonial slider component gt lt div class w full max w xl mx auto text center x data slider gt lt Testimonial image gt lt div class relative h gt lt div class absolute top left translate x w px h px pointer events none before absolute before inset before bg gradient to b before from indigo before via indigo before via before to indigo before to before rounded full before z gt lt div class h mask image linear gradient deg transparent theme colors white theme colors white gt lt Alpine js template for testimonial images x for gt lt template x for testimonial index in testimonials key index gt lt div x show active index class absolute inset z x transition enter transition ease cubic bezier duration order first x transition enter start opacity rotate deg x transition enter end opacity rotate x transition leave transition ease cubic bezier duration x transition leave start opacity rotate x transition leave end opacity rotate deg gt lt img class relative top left translate x rounded full src testimonial img width height alt testimonial name gt lt div gt lt template gt lt div gt lt div gt lt div gt lt Text gt lt div class mb gt lt div class relative flex flex col transition all duration delay ease in out x ref testimonials gt lt Alpine js template for testimonials x for gt lt template x for testimonial index in testimonials key index gt lt div x show active index x transition enter transition ease in out duration delay order first x transition enter start opacity translate x x transition enter end opacity translate x x transition leave transition ease out duration delay absolute x transition leave start opacity translate x x transition leave end opacity translate x gt lt div class text xl font bold text slate before content C after content D x text testimonial quote gt lt div gt lt div gt lt template gt lt div gt lt div gt lt Buttons gt lt div class flex flex wrap justify center m gt lt Alpine js template for buttons x for gt lt template x for testimonial index in testimonials key index gt lt button class inline flex justify center whitespace nowrap rounded full px py m text xs shadow sm focus visible outline none focus visible ring focus visible ring indigo dark focus visible ring slate transition colors duration class active index bg indigo text white shadow indigo bg white hover bg indigo text slate click active index stopAutorotate gt lt span x text testimonial name gt lt span gt lt span class active index text indigo text slate gt lt span gt lt span x text testimonial role gt lt span gt lt button gt lt template gt lt div gt lt div gt lt Slider data and functionality gt lt script gt document addEventListener alpine init gt Alpine data slider gt active autorotate true autorotateTiming testimonials img testimonial jpg quote The ability to capture responses is a game changer If a user gets tired of the sign up and leaves that data is still persisted Additionally it s great to select between formats name Jessie J role Acme LTD img testimonial jpg quote Having the power to capture user feedback is revolutionary Even if a participant abandons the sign up process midway their valuable input remains intact name Nick V role Malika Inc img testimonial jpg quote The functionality to capture responses is a true game changer Even if a user becomes fatigued during sign up and abandons the process their information remains stored name Amelia W role Panda AI init if this autorotate this autorotateInterval setInterval gt this active this active this testimonials length this active this autorotateTiming this watch active callback gt this heightFix stopAutorotate clearInterval this autorotateInterval this autorotateInterval null heightFix this nextTick gt this refs testimonials style height this refs testimonials children this active offsetHeight px lt script gt lt End Fancy testimonial slider component gt Now that we have shown you how simple it is to implement a fancy testimonial slider on your website and landing page all you have to do is start hunting for testimonials to showcase how much your current customers value your product We are aware that this is not an easy task but with a little patience and time you can collect plenty of wonderful testimonials that will delight your visitors and prospects |
2023-06-20 09:01:12 |
海外TECH |
Engadget |
Vimeo's new AI-powered editing tools are designed for beginners |
https://www.engadget.com/vimeos-new-ai-powered-editing-tools-are-designed-for-beginners-091529203.html?src=rss
|
Vimeo x s new AI powered editing tools are designed for beginnersVimeo is one of the latest companies to launch AI powered tools of its own and as you d expect they re geared towards making it easier for creators to edit their videos The video hosting platform says most people lack the skills time or resources to effectively create and edit videos and these features are meant to eliminate those barriers nbsp Perhaps the most useful of the three new AI tools is the text based video editor that can automatically delete long pauses and parts of the video with filler words such as um and ah with just a single click Users will also be able to easily remove any part of the video they want by searching for certain words in the transcript that the tool generates and then clicking delete If they want to create short clips for social media they can search the transcript for a specific word highlight and right click on the word sentence or paragraph and then select keep only this Vimeo has also launched a script generator that can conjure a full script based on a text prompt written by the user the intended video length and the tone such as confident funny or casual they choose According to TechCrunch it s powered by OpenAI s GPT technology made into a part of the editing suite through its API Finally the company has introduced an on screen teleprompter that can display scripts with the font size and the pacing the user sets It could help creators stay on script while maintaining eye contact with the camera All three tools will be available in July as part of Vimeo s Standard and Pro subscription plans While users can test them as part of those plans seven day trial period they ultimately have to pay at least a month when billed annually to be able to keep using them nbsp VimeoThis article originally appeared on Engadget at |
2023-06-20 09:15:29 |
海外科学 |
NYT > Science |
Collective Force of Head Hits Increases Odds of CTE, Study Says |
https://www.nytimes.com/2023/06/20/sports/football/cte-study-concussions-brain-tackle.html
|
Collective Force of Head Hits Increases Odds of CTE Study SaysThe largest study of chronic traumatic encephalopathy to date found that the cumulative force of head hits absorbed by players in their careers is the best predictor of future brain disease |
2023-06-20 09:01:35 |
医療系 |
医療介護 CBnews |
インフルエンザやMRなどのワクチン接種6件認定-厚労省が疾病・障害認定審査会分科会審議結果公表 |
https://www.cbnews.jp/news/entry/20230620173509
|
予防接種 |
2023-06-20 18:15:00 |
金融 |
金融庁ホームページ |
入札公告等を更新しました。 |
https://www.fsa.go.jp/choutatu/choutatu_j/nyusatu_menu.html
|
公告 |
2023-06-20 11:00:00 |
金融 |
金融庁ホームページ |
鈴木財務大臣兼内閣府特命担当大臣閣議後記者会見の概要(令和5年6月16日)を掲載しました。 |
https://www.fsa.go.jp/common/conference/minister/2023a/20230616-1.html
|
内閣府特命担当大臣 |
2023-06-20 10:00:00 |
金融 |
ニュース - 保険市場TIMES |
東京海上日動ら、自動運転導入や運行を支援するサービス提供へ |
https://www.hokende.com/news/blog/entry/2023/06/20/190000
|
東京海上日動ら、自動運転導入や運行を支援するサービス提供へ自動運転の走行前・走行中・事故時の各フェーズに安心・安全を提供東京海上日動火災保険株式会社以下、東京海上日動、東京海上ディーアール株式会社以下、東京海上ディーアール、および株式会社プレミア・エイド以下、プレミア・エイドは年月日、「自動運転向け遠隔監視・インシデント対応サービス」および「自動運転導入・運行支援パッケージ“HawkSafEyeホークセーフアイ」の提供を開始すると発表した。 |
2023-06-20 19:00:00 |
海外ニュース |
Japan Times latest articles |
Joshua Franco feeling strong ahead of rematch with Kazuto Ioka |
https://www.japantimes.co.jp/sports/2023/06/20/more-sports/boxing-2/franco-ioka-rematch/
|
Joshua Franco feeling strong ahead of rematch with Kazuto IokaThe duo s previous bout a super fly unification match at Tokyo s Ota City General Gymnasium on New Year s Eve was a round draw leaving them |
2023-06-20 18:06:24 |
ニュース |
BBC News - Home |
Russia renews drone and missile attacks on Ukraine |
https://www.bbc.co.uk/news/world-europe-65959145?at_medium=RSS&at_campaign=KARANGA
|
attacks |
2023-06-20 09:44:37 |
ニュース |
BBC News - Home |
Rape victims still being 'failed' two years after action promised |
https://www.bbc.co.uk/news/uk-65894060?at_medium=RSS&at_campaign=KARANGA
|
government |
2023-06-20 09:33:16 |
ニュース |
BBC News - Home |
Christopher Nkunku: Chelsea sign RB Leipzig striker for £52m |
https://www.bbc.co.uk/sport/football/64013875?at_medium=RSS&at_campaign=KARANGA
|
bridge |
2023-06-20 09:45:47 |
ニュース |
BBC News - Home |
Titanic sub: Who was on board? |
https://www.bbc.co.uk/news/uk-65955554?at_medium=RSS&at_campaign=KARANGA
|
titanic |
2023-06-20 09:47:29 |
ニュース |
Newsweek |
<動画>ウクライナ特殊部隊、ロシア軍の塹壕で「敵10人を殺害した」映像を公開 |
https://www.newsweekjapan.jp/stories/world/2023/06/10-178.php
|
ウクライナ特殊部隊、ロシア軍の塹壕で「敵人を殺害した」映像を公開ウクライナ兵とロシア兵の接近戦を捉えた分間のビデオウクライナ特殊部隊が塹壕でロシア軍の兵士人を殺害する様子を捉えたとみられる衝撃的な動画が公開された。 |
2023-06-20 18:28:17 |
マーケティング |
MarkeZine |
Openaiサイトへの国別トラフィックシェアで日本は3位/ChatGPTの利用率は約1割/NRI調査 |
http://markezine.jp/article/detail/42550
|
chatgpt |
2023-06-20 18:15:00 |
仮想通貨 |
BITPRESS(ビットプレス) |
GMOコイン、オーエムジー(OMG)の取扱廃止およびネム(XEM)の一部サービス終了へ |
https://bitpress.jp/count2/3_10_13651
|
廃止 |
2023-06-20 18:31:37 |
仮想通貨 |
BITPRESS(ビットプレス) |
コインチェック、2023/7/25付で暗号資産「OMG」を取扱い廃止へ |
https://bitpress.jp/count2/3_10_13650
|
資産 |
2023-06-20 18:26:51 |
IT |
週刊アスキー |
『ペルソナ3 リロード』限定放送されたテレビCM映像がウェブで公開! |
https://weekly.ascii.jp/elem/000/004/141/4141795/
|
公式twitter |
2023-06-20 18:50:00 |
IT |
週刊アスキー |
『LIVE A LIVE』コンサートのチケット一般販売は6月24日10時より開始 |
https://weekly.ascii.jp/elem/000/004/141/4141785/
|
livealive |
2023-06-20 18:15:00 |
IT |
週刊アスキー |
自動運転技術(L4)を搭載した配膳・配送ロボット、ロボットバンク |
https://weekly.ascii.jp/elem/000/004/141/4141781/
|
risubot |
2023-06-20 18:30:00 |
IT |
週刊アスキー |
ローランド、高機能で軽量なポータブルキーボード「E-X10」 |
https://weekly.ascii.jp/elem/000/004/141/4141791/
|
軽量 |
2023-06-20 18:45:00 |
IT |
週刊アスキー |
ツバサ・フロンティア、使いやすいサイズの5L液剤農業用農薬散布ドローン「X1000」および訓練用ドローン「TOMCAT」発売 |
https://weekly.ascii.jp/elem/000/004/141/4141786/
|
tomcat |
2023-06-20 18:15:00 |
コメント
コメントを投稿