If you are using a Bootstrap based theme, then you’ll probably be familiar with many of the built-in components that come with the Bootstrap framework. Most of these components can be implemented directly using data attributes in your HTML and this makes them accessible to us directly from Views.
In this article we are going to be using Views to add a popover directly to our custom post data displayed on the page.
We don’t have to add any styling or create html for the popover, we just need to set data-attributes in our view and one line of jQuery to get it all working.
As you can see from the image above, we have a list of bookings and instead of displaying all details for each booking, we’ve added an info icon next to the name of our client. Clicking on the icon opens a popover with details for the booking.
One of the great features of most of the Bootstrap components, is that we can automate them directly using html. You can see from the above code sample, that we have added the information for the popover as data attributes in our view.
We’ve added a <i></i> fontawsome icon, and wrapped it in an <a> tag. It’s the <a> tag that drives the popover.
If you take a look at the Bootstrap popover documentation, you can see that we have set a tabindex attribute, and the trigger data attribute is set to focus: data-trigger=”focus” – this combination means that the popover will be closed the next time the user clicks the mouse – so no need to worry about close dialogs, fade-outs etc
data-toggle=”popover” tells bootstrap what component we want on the page, and we’ll use this later to trigger the popover.
data-html=”true” lets us add html as popover content. If we are filling our popover with types data we’ll need this.
data-placement=“auto bottom“ specifies where the popover will appear. In this case, below the icon if possible.
title=’[types field=”client-name” id=””][/types]’ the title will be displayed as our popover title. We’ve set it to the Client name for our booking.
data-content='<label>Client email</label><br><span>[types field=”email” output=”raw”][/types]</span><br><label>Client phone</label><br><span>[types field=”phone-number”][/types]</span><br><p>[types field=”comments”][/types]</p>’>
The data content will be displayed in the body of our popover. We are displaying our client email, phone and comments about the booking.
Take a look at the code in the gist (above). You can see we’ve gone a step further and added views conditional statements to only output the email and phone fields when they contain data.
Initializing your popovers
You don’t really want to use popovers from mobile devices. In our bookings example, we only show the popover in large screen mode. For small screens (i.e. smartphones) we hide the popover and display all the details for each booking. You can use the Bootstrap responsive utilities along with the Bootstrap Grid to hide an show different content at different screen sizes.