0

I made a function using jQuery and Ajax to append info from a separate PHP file to another file. Lets call the destination file "Homepage" and the file containing the data "Template".

So i use this function:

var box = $('#infoPageContainer'),
    close = $('.arrow');

btn1.click( function(){
    event.preventDefault();
    if( box.hasClass( 'active' )){
        box.removeClass( 'active' );
        box.css( "width", "0%" );

        $('#placeholder1').fadeOut(600);

        setTimeout(function(){
            $('#placeholder1').html("");
        },1000);

    } else {

        box.addClass('active');
        box.css( "width", "100%" );

        $.ajax({
            url: 'template/parts/Template.php',
            success: function(data){
                $('#placeholder1').html(data).fadeIn(600);
            },

            beforeSend: function(){
                $('#placeholder1').html("loading").fadeIn(600);
            }
        });
    }
});

To append this data:

<div class="mainImgContainer1 templateImgContainer"></div>

<div class="textContainer">

    <img src="img/arrow-01.png" alt="arrow" class="arrow">

    <div class="titleContainer"><h3>Veldopstellingen</h3></div>

    <div class="textWrapper">
        <h4>Dit is de titel</h4>
        <p class="broodTekst">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
    </div>
</div>

As you can see I use a switch that checks for an 'Active' class and runs the respective function. What I want however, is the function removing the appended data to be triggered by a button that is appended (Img with Arrow class). So like this:

close.click( function(){
    event.preventDefault();
    box.removeClass( 'active' );
    box.css( "width", "0%" );

    $('#placeholder1').fadeOut(600);

    setTimeout(function(){
        $('#placeholder1').html("");
    },1000);
});

But when I do so, nothing happens even tho the function does work when I don't use an appended object as trigger. What should I do?

finner10
  • 43
  • 1
  • 8

1 Answers1

0

jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use event delegation, bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally you should delegate to the nearest parent existing at the time of page load.

In your code it will be something like:

$(document).on('click', close, function() {...
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119