Sam Skirrow Sam Skirrow - 4 months ago 19
HTML Question

jQuery populate a div with data-attributes using Ajax

I have a pretty simple task, however, I'm new to working with AJAX so please bare with me.

I have the following (simplified) html code:

<div class="column span-4">
<img src="image1">
<h2>Title 1</h2>
<p>Excerpt 1</p>
<a href="#" class="button package_info" data-title="Title 1" data-img="image1" data-excerpt="Excerpt 1" data-vid="video_url_1">More Info</a>

<div class="column span-4">
<img src="image2">
<h2>Title 2</h2>
<p>Excerpt 2</p>
<a href="#" class="button package_info" data-title="Title 2" data-img="image2" data-excerpt="Excerpt 2" data-vid="video_url_2">More Info</a>

<div class="column span-4">
<img src="image1">
<h2>Title 3</h2>
<p>Excerpt 3</p>
<a href="#" class="button package_info" data-title="Title 3" data-img="image3" data-excerpt="Excerpt 3" data-vid="video_url_3">More Info</a>

<div class="package_overview" style="width:100%;height:100%;top:100%;background:#ffffff;position:fixed;padding:35px;z-index:9999;transition:0.15s ease-out all;">
<div class="package_overview_close"><i class="fa fa-close"></i></div>

The idea here is that when a user clicks on "More info", the div "package_overview" shows, and in that div is the information contained within data attributes on the link they clicked (i.e. data-title, data-excerpt, data-img, data-vid etc - there are more in my actual code, but i'm keeping this simple).

Here is my current jQuery,

$('a.package_info').click(function( event ) {
$('.package_overview_close').click(function( event ) {

Obviously, this just opens and closes the div, but how can I populate it with the data attributes when the user clicks on it?


you can use data() method for manage data-* attributes

$('a.package_info').click(function( e ) {
        var title = $(this).data('title');
        var excerpt= $(this).data('excerpt'); 
        $('.package_overview').html('Title : '+ title + '<br/>' + 'Excerpt : ' + excerpt);
        return false;