Reputation: 841
I wrote a basic slider in Javascript in a practice file and now trying to implement it in my site by converting it to jQuery for efficiency, however with using jQuery it doesn't work. I don't see where I am wrong.
JavaScript
(function Slider() {
var slide = document.getElementsByClassName("slide"),
dot = document.getElementsByClassName("dot"),
slideList = [slide[0],slide[1],slide[2]],
buttonL = document.getElementById('btL'),
buttonR = document.getElementById('btR'),
index = 0;
slideList[0].style.display = 'block';
(function displayDot() {
var dotContainer = document.getElementById('dotContainer'),
dotHtml ='',
i;
for (i = 0; i < slideList.length; i++) {
dotHtml += '<div class="dot"></div>';
}
dotContainer.innerHTML = dotHtml;
}());
dot[0].style.backgroundColor = '#e29f6f';
function slideIt(direction) {
previous = index;
if (direction === 'right') {
index++;
if (index >= slideList.length) {
index = 0;
}
} else if (direction === 'left') {
index--;
if (index < 0) {
index = slideList.length-1;
}
}
slideList[index].style.display = 'block';
slideList[previous].style.display = 'none';
dot[index].style.backgroundColor = '#e29f6f';
dot[previous].style.backgroundColor = 'grey';
}
buttonR.addEventListener('click', function(){ slideIt('right'); }, false);
buttonL.addEventListener('click', function(){ slideIt('left'); }, false);
}());
jQuery attempt
$(document).ready(function() {
var slide = $( ".slide" ),
dot = $( ".dot" ),
slideList = [slide[0], slide[1], slide[2]],
buttonL = $( '#btL' ),
buttonR = $( '#btR' ),
index = 0;
slideList[0].css("display", "block");
(function displayDots() {
var dotContainer = $( "#dotContainer" ),
dotHtml ='',
i;
for (i = 0; i < slideList.length; i++) {
dotHtml += '<div class="dot"></div>';
}
dotContainer.append(dotHtml);
}());
dot[0].css("background-color", "#e29f6f");
function slideIt(direction) {
previous = index;
if (direction === 'right') {
index++;
if (index >= slideList.length) {
index = 0;
}
} else if (direction === 'left') {
index--;
if (index < 0) {
index = slideList.length-1;
}
}
slideList[index].css("display", "block");
slideList[previous].css("display", "none");
dot[index].css("background-color", "#e29f6f");
dot[previous].css("background-color", "grey");
}
buttonL.click(function() {
slideIt('left');
});
buttonR.click(function() {
slideIt('right');
});
});
Upvotes: 0
Views: 36
Reputation: 4689
when you do something like:
$( ".dot" )
You can do:
$( ".dot" ).css(...);
The result is a JQuery collection
But no
$( ".dot" )[0].css(...);
$( ".dot" )[0] is a DOM node
You can do for example:
var elem = $( ".dot" )[0];
$(elem).css(...);
Upvotes: 2