Reputation: 99
I found this script here at Stackoverflow:
https://stackoverflow.com/a/7571867/2518302
When put that code in a normal:
$(document).ready(function () { Script });
.. the script runs good. The problem is that its not affect dynamic loaded content at the site, so if having a div that loads in dynamic (after pageload) the script dont work at that div.
Then if trigger the script to run again at the same time as the dynamic content loads the already existing divs using this script on the page gets the script for its second time since pageload (script executed once at pageload and once at dynamic load). The results of that is that all the divs that got the script twice scroll at double speed.
Is there any way to just execute the script at pageload and make it affect both content thats on page since pageload and later dynamic loaded content?
Thanks for you time.
Upvotes: 2
Views: 1841
Reputation: 113335
Use on
jQuery function.
$(document).on("event", "selectorOfDynamicElements", function() {
// do something
});
In the documentation we find this:
.on( events [, selector ] [, data ], handler(eventObject) )
So in the example we will detect clicks on document
with these parameters:
events
: "click"selector
: ".myFavoriteClass"When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
. To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page.
[read more on the documentation page]
The issue in this fiddle is that you create binds to every mouseover
.
$(document).on('mouseover', '.test', function () {
// the mouseover is detected, "Hey, create a new handler!"
$('.test').bind('mousewheel DOMMouseScroll', function(e) {
// "Ok, sir. Here your code goes"
});
});
Instead of the code above you should simply have:
$(document).on('mouseover mousewheel DOMMouseScroll', '.test', function (e) {
// here your code goes
});
Upvotes: 1
Reputation: 5920
Use on
and delegate to an element that is present when the page loads.
For example, if the dynamically created div
that is not present on page load looks like this
<div id="dynamic"></div>
Your JS
would look like this
$(body).on(event, '#dynamic', function(){ Script });
Where event
is equal to click
, mousedown
, etc.
Upvotes: 0