1
Good afternoon. Practicing a little, I decided to build a javascript slider, and chose to follow this construction line with a builder. The code is functional. However, I would like to encapsulate as much as possible the entire code structure. But I could not fit the following section inside the body of the object:
novoSlider.btnProx.onclick = function () {
novoSlider.prox();
}
novoSlider.btnPrev.onclick = function () {
novoSlider.prev();
}
Complete code:
<script>
var sliderJs = function () {
var elements = [];
var pos = 0;
var btnProx;
var btnPrev;
this.construtor = function (proxId, prevId, objJson) {
this.btnProx = document.getElementById(proxId);
this.btnPrev = document.getElementById(prevId);
elements = objJson;
container.childNodes[1].textContent = elements[pos].titulo;
container.style.transition = "all .3s";
container.style.backgroundImage = "url("+elements[pos].url+")";
};
this.prox = function () {
if(pos != elements.length-1){
pos = pos + 1;
container.childNodes[1].textContent = elements[pos].titulo;
container.style.backgroundImage = "url("+elements[pos].url+")";
}else{
pos = 0;
container.childNodes[1].textContent = elements[pos].titulo;
container.style.backgroundImage = "url("+elements[pos].url+")";
}
};
this.prev = function () {
if(pos != 0){
pos = pos -1;
container.childNodes[1].textContent = elements[pos].titulo;
container.style.backgroundImage = "url("+elements[pos].url+")";
}else{
pos = elements.length-1;
container.childNodes[1].textContent = elements[pos].titulo;
container.style.backgroundImage = "url("+elements[pos].url+")";
}
};
};
window.onload = function () {
var objElements = [
{titulo : "Jogador é demitido",
url : "http://4.bp.blogspot.com/-Vp4z1HqcVWQ/VfcI2mUUjSI/AAAAAAAABMQ/t10j6_O6lEE/s300-c/infidelidade2.jpg" },
{titulo : "Cunha abre processo de impeatchment",
url : "http://www.atoananet.com.br/links/2015/08/11/artista-tranforma-fotos-aleatorias-em-divertidas-ilustracoes_300.jpg" },
{titulo : "MegaSena acumulada",
url : "http://1.bp.blogspot.com/-8rt58bwMhTs/U_1SXIg8FSI/AAAAAAAAEMY/A3DZRYdMGSY/s300-c/cat01.jpg" }
];
var novoSlider = new sliderJs();
novoSlider.construtor("prox","ant",objElements);
novoSlider.btnProx.onclick = function () {
novoSlider.prox();
}
novoSlider.btnPrev.onclick = function () {
novoSlider.prev();
}
}
</script>
The variable
container
is it global? it comes from where?– Sergio
Regarding your question you could ask
this.btnPrev.addEventListener('click', this.prev);
and the same for theprox
– Sergio
It worked. I even tested this, but instead of clicking, I put onclick. Thanks. And container, it’s an element that will contain the slider. it is not directly defined in the code pq the reference is being made directly to the elementc id (as if it were a variable, and it is) without getElementById. Thank you!
– Erick Lemos