The IntersectionObserver is designed to perform functions at certain scroll points. I give these functions in the data-options attribute under callbacks.
Now the question, how can I trigger the corresponding function? That would look like this:
modal ('default-modal');
notify ('subscribe-newsletter', 'bottomLeft');
My HTML node with the JSON string:
<section id="section-90" data-trigger="observer" data-options="{'root':null,'rootMargin':'0px','threshold':[0,0.1,0.2,0.3,0.4,0.7,1],'callbacks':{'modal':[{'id':'default-modal','position':'center'}],'notify':[{'id':'subscribe-newsletter','position':'bottomLeft'},{'id':'become-distributor','position':'bottomRight'}]}}">
Formatted JSON (Only here for a better overview:):
{
"root": "null",
"rootMargin": "0px",
"threshold": [
0,
0.25,
0.5,
0.75,
1
],
"callback": {
"modal": [
{
"id": "default-modal",
"position": "center"
}
],
"notify": [
{
"id": "subscribe-newsletter",
"position": "bottomLeft"
},
{
"id": "become-distributor",
"position": "bottomRight"
}
]
}
}
Parse String with options and filter callbacks
let str = target.dataset.options; // options from HTML node
let optStr = str.replace(/'/g, '"');
options = JSON.parse(optStr);
let callbacks = options.callbacks; // store only callbacks
for (const key of Object.keys(callbacks)) {
console.log(key, callbacks[key]);
/*
Output:
modal -> [{"id":"default-modal"}]
notify -> [{"id":"subscribe-newsletter","position":"bottomLeft"},{"id":"become-distributor","position":"bottomRight"}]
*/
}
How can I call the function with arguments from the output?
modal('default-modal');
notify('subscribe-newsletter', bottomLeft)