Popover API Feature ใหม่ที่ช่วยให้เราทำ popup ง่ายๆ แถมใช้ได้ทุก Browser (แต่จริงๆมันก็มี Dialog…

หลังจากที่ Experiment กันอยู่หลายเดือนตอนนี้ Popover API ก็พร้อมใช้บน ทุก Browser แล้ว แต่ก่อนอื่นต้องมาเล่ากันก่อนว่า Popover API คืออะไร Popover API เป็น Feature บนเว็บที่ทำให้เราสามารถสร้าง Element แบบที่เป็น Lightbox บนหน้าเว็บโดยไม่ต้องพึ่ง Lib ได้โดยที่การเปิดปิด element นี้ สามารถกำหนดใน HTML Element ได้เลย

<button popovertarget="my-popover"> Open Popover </button>
<div id="my-popover" popover>
<p>I am a popover with more information. Hit <kbd>esc</kbd> or click away to close me.<p>
</div>
view raw popover.html hosted with ❤ by GitHub

ซึ่งถ้าใครเคยใช้พวก Lib ที่เป็น Javacsript ก็จะเห็นว่ามีวิธีการใช้งานที่ค่อนข้างใกล้เคียงกันมากๆ ซึ่งในเวลาเดียวกันถ้าใคร อยากจะทำ ปุ่มปิด ตัว popover element ก็เปิดให้เราทำตัวปุ่มปิดง่ายๆได้เลย แค่ใส่ element ที่มี attribute popovertarget="my-popover" popovertargetaction="hide" ไว้ก็จะกลายเป็นปุ่มปิดได้เลย

<button popovertarget="my-popover" class="trigger-btn"> Open Popover </button>
<div id="my-popover" popover=manual>
<p>I am a popover with more information. Hit the close button or toggle to close me.<p>
<button class="close-btn" popovertarget="my-popover" popovertargetaction="hide">
<span aria-hidden="true">❌</span>
<span class="sr-only">Close</span>
</button>
</div>
view raw popover2.html hosted with ❤ by GitHub

นี่ก็เป็นตัวอย่างที่ผมลองเขียน Popover ง่ายๆ

เรามี Dialog Element อยู่แล้วไม่ใช่หรอ…..

ใช่ครับ!!! นั่นคือคำถามแรกเลยที่ผมถามตอนเห็น API นี้ ซึ่งพอไปดู Spec แล้วมันก็มีความต่างกันจริงๆแหละ แต่เป็นความต่างแบบแปลกๆ เพราะเหมือนแทนที่จะเพิ่ม Feature ให้ Dialog แต่กลับมาทำ Popover API เป็นอันใหม่ ซึ่งสิ่งที่ต่างกันระหว่าง Dialog Element กับ Popover Api ก็จะมีตามนี้

1. Dialog element ต้องเปิด / ปิดด้วย function Javascript ที่ชื่อว่า showModal หรือ Close แต่ Popover เป็นการเอา Element ไปผูกกับ Element นึง แล้วก็เวลาทำปุ่มปิดก็ทำคล้ายๆกัน

2. By default แล้ว Dialog จะปิดได้ต้อง implement ปุ่มปิดมาเท่านั้น ถ้าไม่มีมันก็จะคาอยู่แบบนั้น แต่ Popover ถ้าเราคลิก element นอก Popover มันก็จะปิดเอง

เอาจริงๆก็จะมีสองอันนี้ที่ต่างกันนอกนั้นก็เป็นแค่วิธีการเขียน CSS ที่ต่างกันเท่านั้นเอง มาถึงตรงนั้นี้แล้วผมก็ยังสงสัยอยู่ดีว่าทำมาสองอันทำไมนะ…

Reference

https://web.dev/blog/popover-api?hl=en#popover_versus_modal_dialog


Discover more from Thangman22's

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from Thangman22's

Subscribe now to keep reading and get access to the full archive.

Continue reading