Pavol
Pavol

Reputation: 88

jQuery, Uncaught TypeError

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:

"Property '$' 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?

Upvotes: 5

Views: 56282

Answers (5)

Ronan
Ronan

Reputation: 4321

(function ($) {
    // All your code here
})(jQuery);

This fixed the problem for me.

Upvotes: 1

jerjer
jerjer

Reputation: 8770

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

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
});

Upvotes: 9

kgiannakakis
kgiannakakis

Reputation: 104178

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

Upvotes: 4

Graviton
Graviton

Reputation: 83254

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.

Upvotes: 0

Related Questions