views:

614

answers:

4

Hi, I have some javascript code on my webpage that is loading some divs onto the page. I also want to add onmouseenter, and onmouseleave event handlers to each div. I am using jquery to add these handlers, but i get the error:

"Prpoerty '$' of object [object DOMWindow] is not a function"

My code looks like this, it is in a for loop:

            var newItem = document.createElement('div');
            newItem.innerHTML = results[i];
            newItem.setAttribute("id", "resultDiv_" + i.toString());
            dropDown.appendChild(newItem);

            //Error on next line...
            $("resultDiv_" + i.toString()).bind("mouseenter", function() {
                $("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
            });

Does anyone have any ideas why i am getting this error, or even what the error means?

Thanks in advance,

Pavol

A: 

What about trying this?

      var newItem = document.createElement('div');
        newItem.innerHTML = results[i];
        newItem.setAttribute("id", "resultDiv_" + i.toString());
        dropDown.appendChild(newItem);

        //Error on next line...
        $("resultDiv_" + i.toString()).mouseenter( function() {
            $("resultDiv_" + i.toString()).css({ 'background-color': 'blue' });
        });

Or make sure that $("resultDiv_" + i.toString()) is not null. Use Firebug to inspect the element.

Ngu Soon Hui
A: 

Are you sure that jQuery is properly loaded? Could it be a conflict with another javascript library?

kgiannakakis
Thanks for the help, turns out i wasn't loading jQuery properly :(
Pavol
A: 

Try replacing all occurrences of $ with jQuery.

Also the selector $("resultDiv_" + i.toString()) won't likely return any elements. You probably meant: $("#resultDiv_" + i.toString())

And finally make sure this code is executed when the DOM is ready i.e. inside:

jQuery(function() {
    // Put your code here
});
Darin Dimitrov
thanks for the suggestion, i replaced $ with jQuery, but i still get the error, with 'jQuery' instead of '$' now. also added the #
Pavol
A: 

You might as well try this:

  var newItem = jQuery('<div id="' + "resultDiv_" + i.toString() + '">+ results[i] + '</div');
  jQuery(dropDown).append(newItem);
  //Error on next line...
  newItem.mouseenter(function(){
      jQuery(this).css( 'background-color', 'blue');
  });

or perhaps jQuery.noConflict will solve this.

jerjer