Luis Dos Reis
Luis Dos Reis

Reputation: 393

jQuery not working on dynamically generated divs

I am creating a portfolio section of a website which utilizes Flickr's REST api. The list of portfolio items, however, is generated dynamically by this code:

$.ajax({
  url: "https://api.flickr.com/services/rest?method=flickr.photoSets.getList&user_id=********@N04&format=json&nojsoncallback=1&api_key=***********",
  context: document.body
}).done(function(results) {
  results.photosets.photoset.map(function(item) {
    var imgUrl = "https://farm" + item.farm + ".staticflickr.com/" + item.server + "/" + item.primary + "_" + item.secret + "" + ".jpg";
    $(" #portfolio_horizontal_container ").append(
      '<div class="portfolio_item interior design"> \
          <img  src=' + imgUrl + '    alt="" /> \
          <div class="port-desc-holder"> \
              <div class="port-desc"> \
                  <div class="grid-item"> \
                      <h3><a href="folio-single">Quisque non augue</a></h3> \
                      <span>Photography /   Web design</span> \
                  </div> \
              </div> \
          </div> \
      </div>'
    )
  })
});

I also have another plugin which manages the portfolio interactions and style. However when the DOM elements for the portfolio items get loaded this other plugins just doesn't work, thus the functionality it applies to the portfolio is non existent. I have tried and tried to solve this with no success. Any thoughs?

Upvotes: 0

Views: 119

Answers (2)

Kim Aragon Escobar
Kim Aragon Escobar

Reputation: 166

If I understood your problem, you could create a function which create the event and call it in the ajax done:

    function bindEvent(id){
         //initialize the plugin for the given id
    }

then you can call bindEvent, after the append inside the ajax.done using the id of the newly inserted html.

or

If it's an event that you want to bind you can use

$('body').on('click', 'my-dinamic-id', function(){...})

Upvotes: 0

Mark
Mark

Reputation: 569

The code that attaches event handlers to your DOM elements will need to be re-run whenever new elements are added to the page.

In the same function as above, you'll need to re-invoke the plugin so that it will be aware of the new structure.

Upvotes: 2

Related Questions