Possible Duplicate:
jQuery: Checking if next element exists
I’m implementing a custom slider using jquery. There I want to give facility to load next/previous image when user press right/left keys respectively.
It is working fine but when cursor reach last/first element, code breaks as it do not find further elements. My code is as follow:
function movePointer(dir){
var selected = $("#imgslider > ul > li > img.siddslideselected");
console.log(selected);
var selectedli = selected.parent();
if(dir=='left'){
var nabourele = selectedli.prev()
}else if(dir=='right'){
var nabourele = selectedli.next();
}
console.log(nabourele);
if(nabourele){
selected.removeClass('siddslideselected');
nabourele.children().addClass('siddslideselected').trigger('click');
}
}
If current position of cursor is in middle, everything work fine but if cursor is on first element, pressing left key breaks the code. I try to stop that by checking if(nabourele){, but it is not working. console log for nabourele show [] in that case.
How can I test condition if next/prev element exist or not?
You have to test the
lengthproperty: