Reputation: 63
I have a galleria object with x images and everytime I go to the page, the first image is displayed. But I want to display maybe the second image, depending on a method return value.
I know that the displayed image has the value display: list-item, and all others have display: none, but I have no idea how to set it programmatically.
Any ideas apprechiated, Ralf!
Upvotes: 0
Views: 1064
Reputation: 10048
You can achieve this by either of these approaches, depends on your needs:
First approach:
A manual selection after the page loads, for example like this:
xhtml
<p:galleria widgetVar="galleriaWV">
...
</p:galleria>
js
<script>
//<![CDATA[
function changeActiveIndex(widgetVar, index, reposition) {
if (widgetVar && index) {
widgetVar.select(index, reposition);
}
}
$(document).ready(function () {
setTimeout(function () {
changeActiveIndex(PF('galleriaWV'), 2, false);
}, 500);
});
//]]>
</script>
This approach will have the following result:
Selecting the third image (bat3.jpg,index = 2), you will notice that the user first sees the 0 activeIndex by default (bat1.jpg) then after a few milliseconds the select takes effect, that's due the call of setTimeout
, the reason behind that call in the docuemnt.ready
is to make sure the widgetVar
is initialized before making the call, preventing having errors like undefined
object, however it's tricky to reduce it, because setTimout can be inaccurate.
Second approach:
This approach would be to monkey patch the _render function, since it's called just once, at the init, this will make sure the image is selected instantly with no delay in the contrary of the first approach.
<script>
//<![CDATA[
function changeActiveIndex(index) {
var oldRender = PrimeFaces.widget.Galleria.prototype._render;
PrimeFaces.widget.Galleria.prototype._render = function () {
this.cfg.activeIndex = index;
oldRender.apply(this, []);
}
}
changeActiveIndex(2);// to get the active image from bean, replace 2 with #{beanName.intIndexOfActiveImage} for example
//]]>
</script>
To note here, in this approach, you are changing all the Galleria components included in that page, for example if you have two Galleria defined in the same final page, they all end up with the same active index, if you have that case, you can check the widgetVar name for equality and execute accordingly.
I would go with the second approach, as it seems more natural from a UX point of view.
Upvotes: 1