Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery populate a div with data-attributes using Ajax

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>

<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>

    <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>

<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>
</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,

jQuery(function($){
        $('a.package_info').click(function( event ) {
        event.preventDefault();
        $('.package_overview').css('top','0');
    });
    $('.package_overview_close').click(function( event ) {
        $('.package_overview').css('top','100%');
    });

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

Upvotes: 0

Views: 283

Answers (2)

Haresh Vidja
Haresh Vidja

Reputation: 8496

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

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

Upvotes: 1

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

Use prop to get attributes of anchor link clicked and populate the html inside using html() function.

$('a.package_info').click(function( event ) {
        event.preventDefault();
        $('.package_overview').css('top','0');
        var title = $(this).prop('data-title');
        var excerpt= $(this).prop('data-excerpt'); 
        .
        .
        $('.package_overview').html('Title : '+ title + '<br/>' + 'Excerpt : ' + excerpt);

  });

Upvotes: 1

Related Questions