Good afternoon. Practicing a little, I decided to build a slider in javascript, and I chose to follow this line of construction with a constructor. The code is functional. However, I would like to encapsulate the entire code structure as much as possible. But I could not fit the following snippet into 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>