I have a fairly standard star voting functionality in my app that uses jQuery’s hover event. The partial that the star voting logic is in used to be rendered with the rest of the page once the DOM was initially loaded (HTML request). However, I would like to move the partial so that it’s not loaded with the page but can be loaded when the user wants. I made a typical AJAX request to load the partial but when it gets rendered the stars don’t react properly to events like a mouseover. Is this issue being brought on because I’m rendering the forms via AJAX or is there just a bug in my code? Thanks for the help
Update: Got it working using the on handler, thanks for the help all!
You are likely trying to bind events to nodes that don’t exist in the DOM yet. The best way to solve this is to bind to a listener that exists prior to the Ajax request, that is an ancestor (sometimes incorrectly called “parent”, which is only one level of ancestor) of the content being fetched. For example, given this markup in the page itself:
“ajaxContainer” is an ancestor of whatever you’re going to fetch. Then you need to bind a listener using an appropriate method. In the old days you could use
live()but it’s deprecated and was not so efficient anyhow. Then the recommendation was fordelegate(), which solved efficiency problems. Now it’s for a delegated listener syntax ofon(), which is roughly the same performance asdelegate()but with different syntax.All that to say, use
.on()if you are using jQuery 1.7+.Imagine your Ajax function retrieves a portion of a page containing your star system mouseover, which is inside a series of divs classed as “stars”. The syntax might look like:
This says “Start listening inside ajaxContainer for events that match ‘mouse enters stars divs’ and when that happens, do stuff.”