0

I am trying to sort out a problem I am having with JQuery. When I dynamically create elements in the DOM, the associated events don't seem to trigger (e.g.: .hover). Not sure if, when creating elements dynamically, do I have to attach the element events somehow?

HTML Code:

    <div id="dosages" style="display:none;">
        <h4>Choose a dosage</h4>
        <ul id="dosagesUL" class="thumbnails">
        </ul>
    </div>

Jquery/Javascript:

    $("#medsSelect").change(function () {

    var dosages = [];
    var dosage;
    var caption;
    var image;
    var html;
    var idx;

    $("#medsSelect option:selected").each(function () {

        idx = $(this).attr("value");

        for (i = 0; i < medsArray[idx][1].length; i++) {

            dosage = medsArray[idx][1][i];
            caption = medsArray[idx][2][i];
            image = medsArray[idx][3][i];

            html =  "<li class=\"span2\">";
            html += "<div id=\"dosageIdx-\" + idx>";

            html += "<div class=\"thumbnail\">";
            html += "<img src=\"img/meds/" + image + ".png\">"
            html += "</div>";

            html += "<div class=\"thumbnail-capbox\">";
            html += "<div class=\"med-label\">" + dosage + "</div>";
            html += "<div class=\"med-caption\">" + caption + "</div>";
            html += "</div>";

            html += "</div>";
            html += "</li>";

            dosages.push(html);
        }

    });

    $("#dosages").fadeOut(0);
    $("#dosagesUL").empty();
    $("#dosagesUL").append(dosages.join(''));
    $("#dosages").fadeIn(600);

    })

    $('div[id*="dosageIdx-"]').hover(

        function () {
            alert('in');
        },

        function () {
            alert('out');
        }
    );
Cœur
  • 37,241
  • 25
  • 195
  • 267
Telegard
  • 137
  • 3
  • 12
  • 1
    - [Event binding on dynamically created elements](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Sen Jacob Apr 16 '13 at 05:09
  • - [In jQuery, how to attach events to dynamic html elements](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Sen Jacob Apr 16 '13 at 05:12
  • - [Adding jQuery click events to dynamically added content](http://stackoverflow.com/questions/852450/adding-jquery-click-events-to-dynamically-added-content) – Sen Jacob Apr 16 '13 at 05:12
  • Thanks for the links, so just for clarity, all dynamically created elements require you manually attach event handlers to them? (e.g.: .hover)? – Telegard Apr 16 '13 at 05:13
  • - [jQuery binding events to dynamically loaded html elements](http://stackoverflow.com/questions/6400343/jquery-binding-events-to-dynamically-loaded-html-elements) – Sen Jacob Apr 16 '13 at 05:13
  • 1
    @Telegard - yes or you can delegate these events, using `.on()` or `.delegate()`. Delegated events are attached to the closest static parent element, in the DOM at the time of execution of your script. – ahren Apr 16 '13 at 05:14
  • @Telegard Read the related questions before asking new questions. The same question is asked many times. :) – Sen Jacob Apr 16 '13 at 05:17
  • @ahren - Thanks for the note... I can attach the handlers, I just wasn't sure if that was the best practice for simple dynamic elements? Am I missing something simpler? In other words is adding event handlers the only (most correct) way to handle dynamic elements? Just want to make sure I am following best practice :) – Telegard Apr 16 '13 at 05:19

2 Answers2

2

Use on():

$('body').on('mouseover', 'div[id*="dosageIdx-"]', function() {
        alert('in');
    }
);
$('body').on('mouseout', 'div[id*="dosageIdx-"]', function() {
        alert('out');
    }
);

However, I suggest you give those divs a common class name, and use that as the second selector instead.

Change this line: (by the way this line is invalid JS syntax if you actually wanted to print the variable idx)

html += "<div id=\"dosageIdx-\" + idx>";

to:

html += "<div id=\"dosageIdx-" + idx + "\" class=\"specialHoverDiv\" \">";

and now you can do this instead of a complicated selector:

$('body').on('mouseover', '.specialHoverDiv', function() {
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
1

you should use on delegated event for dynamically added element..

 $(document).on('click','#elementID',function(){
       alert("clicked");
 })

and for hover, since on() and hover() cannot be used you can use mouseenter and leave instead

 $(document).on(
 {
  mouseenter: function() 
  {
    alert("mouseenter");
  },
  mouseleave: function()
  {
    alert("mouseleave");
  }
 }, '#elementID');  

it is always recommended to delegate your event to the closest static parent element than the document... which in your case is #dosagesUL (i think)... and yes using class if you have multiple ID is always better..

  $('#dosagesUL').on(
  {
    .....
bipen
  • 36,319
  • 9
  • 49
  • 62