Reputation: 7845
I wrote this small JQuery plugin to load content on a specific DOM element according to the hashchange, but I'm having problems making MaterializeCSS's carousel work.
Here's home.html:
<div class="carousel">
<a class="carousel-item" href="#one!">
<img src="src/assets/carousel_slide_0.jpg">
</a>
<a class="carousel-item" href="#two!">
<img src="src/assets/carousel_slide_1.jpg">
</a>
<a class="carousel-item" href="#three!">
<img src="src/assets/carousel_slide_2.jpg">
</a>
</div>
Here's my index.js:
import "materialize-css/dist/js/materialize.min.js"
import "materialize-css/dist/css/materialize.min.css"
import "styles/vovojo.less"
import "./hashy-content.js"
$(document).ready(function () {
$(".dropdown-trigger").dropdown({
hover: true,
constrainWidth: false
});
$("#content").addHash("index", "src/content/home.html");
$("#content").addHash("quem-somos", "src/content/quem_somos.html");
$("#content").addHash("contato", "src/content/contato.html");
$().watch();
});
As I've attached the "index" hash to that "home.html" file, each time the hash changes to #index
, the content of home.html
gets loaded inside a "content" ID. Problem is, when the DOM of index.html is ready and the hash gets attached to that home.html, the .carousel
element does not exist yet, so when the content gets loaded (jQuery.load()), the carousel doesn't work. If I associate a function to get called after the content has been loaded, I get all sorts of bugs regarding other dependencies.
So, Is it possible to apply a method on an element that has not been loaded yet? (To make a promise somehow / "wait")
Like:
$(document).whenNonExistentElementIsReady(function() { $("#NonExistentElement").doSomething(); });
Upvotes: 1
Views: 102
Reputation: 7845
I'll give Ringo's the right answer because it's right (When I've attached the "click" event to the body, I've managed to make the carousel work after the click). I've found a rather obscure solution to my specific problem, that I'll include here for future users:
$("#content").bind("DOMSubtreeModified", function () {
$(".carousel").carousel();
});
Now, each time the HTML/DOM structure of that element gets modified, the code runs (Which is exactly what I needed).
Upvotes: 0
Reputation: 5483
You might benefit from using jQuery.on().
https://www.w3schools.com/jquery/event_on.asp
.on() method attaches events to FUTURE elements as well as currently-existing ones.
Upvotes: 2