vibz
vibz

Reputation: 79

How to create a new div onclick using jQuery

I'm working on a task I need to display Post Content-Img-Title on click without reload the page.

I've coded Below code:

// code for ajax portfolio
jQuery('span#ajax_post_abc a').click(function(){
    var portfolio_post_id= jQuery(this).attr('id');
    var ajaxurl = jQuery('#ajax-script-url').val();

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,        
        data: {
            "action": "load-filter2", 
            port_post_id: portfolio_post_id 
        },
        success: function(response) {
            jQuery(".aajax-post-content").html(response); }  
        });
    });

    //New Ajax portfolio div 
    jQuery('#ajax_post_abc').click(function() {
        jQuery(this).addClass('aajax-post-content');
    });  

And the resultant response in will be displayed in aajax-post-content div. But the problem is if I have n posts and I click on n+1, n+2 and so on it does not shows the output. But if I click on the very first Post n0 then it will show the output as I need.

Upvotes: 0

Views: 4360

Answers (6)

Nandakumar
Nandakumar

Reputation: 1101

Use On method instead of Click function because when multiple clicks are to be included,it never works,So Change your code as

$(document).on( 'click','#ajax_post_abc', function (e) {
    jQuery(this).addClass('aajax-post-content');
});

Thank You Vibz...

Upvotes: 0

avrahamcool
avrahamcool

Reputation: 14094

replace #content with any selector you want.

$('<div>new content</div>').appendTo($('#content'));

Upvotes: 0

sun
sun

Reputation: 1668

Try this

jQuery('span#ajax_post_abc a').click(function(){
    var portfolio_post_id= jQuery(this).attr('id');
    var ajaxurl = jQuery('#ajax-script-url').val();

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,        
        data: {
            "action": "load-filter2", 
            port_post_id: portfolio_post_id 
        },
        success: function(response) {
            jQuery(".aajax-post-content").html(response);
            jQuery(#ajax_post_abc).addClass('aajax-post-content');
             }  
        });
    });

Upvotes: 0

Arun
Arun

Reputation: 257

content.append('<div class="item"><span>' +data + '</span></div>');

Upvotes: 2

kinghfb
kinghfb

Reputation: 1021

jQuery.html() replaces the inner html of the item. jQuery.append() adds a new element as a child to the specified container.

Sounds like you need append()

Upvotes: 0

Scription
Scription

Reputation: 645

Your code will only show the most recent change which happened.

If you want to see each change you must append the changes and use .append instead of .html

for example:

jQuery(".aajax-post-content").append(response);

Upvotes: 0

Related Questions