1

I made a webpage "items.php" to which I added a hidden <p> element that has the contents of the URL GET parameter passed to the page. Then I made it so on document.ready I call a setup() function immediately. (This is in items.js which is added in a script tag at the bottom of items.php)

This setup function reads the contents of this hidden <p> element and makes an ajax call and the data echoed in the php is added in the made container (<div>) of the page. (Requests to the databases are made and checkboxes are made based on this hidden <p> and other input data is generated as well).

Now here is the problem:

From a visual standpoint everything is on point (I made some color checkboxes of my own, div elements) ALMOST. My jQuery UI range sliders aren't there.

Also, events to the created markup I cannot catch in my items.js. I am supposed to have a toggle happen on a click on my colored checkboxes I created. Now, all this worked when data wasn't dynamically generated, but now it does not. I even added the listeners after the setup function like so, for example:

$(document).ready(function() {
  setup();
  $(".colorbox" ).click(function(){
    $(this).children().toggle();
  });    
});

This is my javascript. I cannot get the custom event to trigger:

function setup() {
    var determinant = $("#cat").text();
    $.post('../phpdatabase/setup.php', {
        categorija: determinant
    }, function(data) {
        $('#content').empty();
        $('#content').append(data);
    });
};



$(document).ready(function() {
    setup();
    $('body').on('click', '.colorbox', function() {
        $(this).children().toggle();
    });
    $('body').on('myCustomEvent', '#slider-range2', function() {
    alert("hye!");
     });
    $('body').trigger('myCustomEvent');

});

myCustomEvent isn't being triggered. Without the second argument, in the handler, it is triggered.

Bocko
  • 33
  • 5

1 Answers1

1

You can attach the event to the body and then the selector you want.. This will work for all elements with class '.colorbox' in the body, whether already present or dynamically added later.

Code:

$('body').on('click', '.colorbox', function(){
   $(this).children().toggle();
});

For the jQuery UI Slider you can also create your own event 'elements-created-dynamically-with-php' and fire it when you add the dynamic content.

Attach event handler:

$('body').on('elements-created-dynamically-with-php', '#slider-range2', function () {
  var $slider = $(this),
      $amount1 = $('#amount1');

  $slider.slider({
    range: true,
    min: 0,
    max: 400,
    values: [0, 400],
    slide: function (event, ui) {
      $amount1.val(ui.values[0] + 'cm' + ' - ' + ui.values[1] + 'cm');
    }
  });

  $amount1.val($slider.slider('values', 0) + 'cm - ' + $slider.slider('values', 1) + 'cm');
});

And when the content is added fire the event:

$('body').trigger('elements-created-dynamically-with-php');
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46