Please excuse the poorly worded title, hopefully I can explain the issue here.
I’ve written a simple gallery control in jQuery, there’s six images with two button controls that allow the user to cycle through a total collection of images. I have this part working fine but whenever I click a button to move through the collection the page ‘jumps/scrolls’ automatically to the top of the page? I’ve tried giving the gallery container a fixed height as I had a similar issue before which I managed to solve doing this but this hasn’t helped:
Here is the jQuery:
var index = 0;
$(function () {
$('#btnLeft').click(function () {
if (index != 0) {
index--;
$('#sixth').attr('src', $('#fifth').attr('src'));
$('#fifth').attr('src', $('#fourth').attr('src'));
$('#fourth').attr('src', $('#third').attr('src'));
$('#third').attr('src', $('#second').attr('src'));
$('#second').attr('src', $('#first').attr('src'));
$('#first').attr('src', '/Content/Images/Gallery/Thumbs/' + parseInt(index + 1) + '.png');
}
});
$('#btnRight').click(function () {
if (parseInt(6 + index) != 10) {
index++;
$('#first').attr('src', $('#second').attr('src'));
$('#second').attr('src', $('#third').attr('src'));
$('#third').attr('src', $('#fourth').attr('src'));
$('#fourth').attr('src', $('#fifth').attr('src'));
$('#fifth').attr('src', $('#sixth').attr('src'));
$('#sixth').attr('src', '/Content/Images/Gallery/Thumbs/' + parseInt(6 + index) + '.png');
}
});
});
Here is the markup:
<div id="gallerySlider" style="height: 160px;">
<img id="first" src="/Content/Images/Gallery/Thumbs/1.png" alt="Image" width="160" height="160" style="float:left;" />
<img id="second" src="/Content/Images/Gallery/Thumbs/2.png" alt="Image" width="160" height="160" style="float:left;" />
<img id="third" src="/Content/Images/Gallery/Thumbs/3.png" alt="Image" width="160" height="160" style="float:left;" />
<img id="fourth" src="/Content/Images/Gallery/Thumbs/4.png" alt="Image" width="160" height="160" style="float:left;" />
<img id="fifth" src="/Content/Images/Gallery/Thumbs/5.png" alt="Image" width="160" height="160" style="float:left;" />
<img id="sixth" src="/Content/Images/Gallery/Thumbs/6.png" alt="Image" width="160" height="160" style="float:left;" />
<a id="btnLeft" style="position:relative; float:left; bottom:105px;" href="#"><img src="/Content/Images/Design/leftbutton.png" alt="Left Button" /></a>
<a id="btnRight" href="#" style="position:relative; float:right; bottom:105px;"><img src="/Content/Images/Design/rightbutton.png" alt="Right Button" /></a>
</div>
Can anyone offer advice?
Thanks
Use
.preventDefault()like following to stop browser default load and jump: