-1

I am trying to add a mouseover function to dynamically created elements using jquery

$('#schools').append(
    '<div class="mediumListIconTextItem" onclick="javascript:showSchoolReport(\'' + $.trim(this.id) + '\',\'' + $.trim(this.companyID) + '\',\'' + $.trim(this.companyCode) + '\',\'' + $.trim(this.companyName) + '\');" style="padding-left: 30px;margin: 5px;">' + '<div class="icon-newspaper mediumListIconTextItem-Image"></div>' + '<div class="mediumListIconTextItem-Detail">' + '<h6 id="header" style="max-width:100px; overflow:hidden;">' + this.name + ' - ' + this.companyName + '</h6></div></div>');

code for mouseover effect

$(document).ready(function (e) {
    $(".mediumListIconTextItem").mouseover(function () {
        alert($(this.name));
    });
});
$(".mediumListIconTextItem").on("mouseover", function () {
    alert('mouseover works!!!!!!!!!');
});
});

none of the above function for mouseover works. whats wrong with my code. suggest a solution

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
user2291144
  • 65
  • 4
  • 14

5 Answers5

2

This is the case called event delegation. In here you can't bind the direct event to a dynamically created elem. try this as below:

$(document).on("mouseover", ".mediumListIconTextItem", function() {
   alert('mouseover works!!!!!!!!!');
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You're almost there, you have to use on but in a different form. You're using direct event but you need to use delegated events

$('#schools').on("mouseover", ".mediumListIconTextItem", function() { .. }

For more details check section Direct and delegated events

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
0

Use on() for dynamically added elements like,

$(document).on("mouseover", ".mediumListIconTextItem", function() {
       alert('mouseover works!!!!!!!!!');
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

Use .on()

As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.

$(document).on("mouseover", ".mediumListIconTextItem", function() { .code here. }

better use

$("#schools").on("mouseover", ".mediumListIconTextItem", function() { .code here. }

Syntax

$( elements ).on( events, selector, data, handler );
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
0

Use event delegation :

$('#schools').on('mouseover', '.mediumListIconTextItem', function(){ ... })

For a clear and short explanation of how event delegation works, see this question :

Direct vs. Delegated - jQuery .on()

Community
  • 1
  • 1
LeGEC
  • 46,477
  • 5
  • 57
  • 104