42

I have searched high and low for an answer and have found similar examples of the problem but the answers do not apply to my scenario. The reality is I am new to this and therefore I don't have the skills to adapt the answers I have found to my problem.

The problem:

I have a Div in which when a thumbnail is clicked the Div image replaces with another image via a JavaScript/jQuery script (I am not sure exactly maybe someone could clarify). This works fine however the problem is the page scrolls back to the top and the user then has to scroll back down to see the image after it has replaced itself.

I have looked online and have found that a return false: in the JavaScript may help however I have looked and return false is already present.

The other option I have looked at using is a JavaScript cookie based solution in which a cookie is sent, and the browser scroll position is maintain by reading the cookie however I cant seem to get that solution to work, I think the issue may be caused because I am hosting locally but I may be wrong...

The third is using a PHP script but I have not found a definitive answer on this method and it also means I am going to have to learn about PHP (something I'm sure I will have to learn in time anyway).

Here is the JavaScript:

<script type="text/javascript">

 $(document).ready(function() {
  $('.galleryicon').live("click", function() {

    $('#mainImage').hide();
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#mainImage').attr('src', i.attr('src'));
        $('#cakebox').css('background-image', 'none');
        $('#mainImage').fadeIn();
    });
    return false; 
   });
 });

</script>

Here is the html:

<div class="cakecont">

  <div id="cakebox">

 <img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>

     <div class="pageinfo2">
     <h3>Cake Type 1</h3>
     <h6>£2.00</h6>
     </div>
     <div class="infobox">
     <h6> Description </h6>
     </div> 

      <div class="gallerybox">
      <a href="../images/cakes/babycaketop.png" class="galleryicon">
      <img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>

      <a href="../images/cakes/babycake1.png" class="galleryicon">
      <img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
   </div>
  </div>
</div>

And here is a link to the working demo http://micahcarrick.com/code/jquery-image-swap/index.html

I have tried to resolve this on my own. This is the first question I have had to ask so far regarding the building of my website, all my learning and remedies to past problems have been served by Google, this one has eluded my search engine skills.

Below I have added all the html for the page in case there may be other script overriding the "new" modified JavaScript -

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org     /TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml"><head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Cupcakes &amp; Cakes for Birthday/Wedding Gift in Bournemouth Dorset - SweetVision</title>
   <meta name="keywords" content="cupcakes, cake, gift, wedding, birthday, Bournemouth, Dorset" />
 <meta name="description" content="For the finest Cupcakes and Cakes in Bournemouth Dorset look no further, Sweetvision specialise in baked goods for Weddings, Birthdays, Baby Showers, Easter, Halloween, Christmas" />
 <meta name="robots" content="ALL" />
 <meta http-equiv= "Content-Language" content="en" />
 <meta name="Publisher" content="Sweet Vision" />
 <meta name="Copyright" content="Copyright 2012, Sweet Vision, All rights reserved." />
 <meta name="Author" content="Mark Webb for Sweet Vision - www.sweetvision.co.uk" />

  <link href="../images/homepage/favicon.ico" type="image/vnd.microsoft.icon" rel="shortcut icon" />

  <link href="../root/css/sweetvision.css" rel="stylesheet" type="text/css" />

  <script src="../js/jquery-1.4.2.min.js" type="text/javascript"></script>

  <script type="text/javascript">

 $(document).ready(function() {   
$('.galleryicon').live("click", function(e) {  // the (e) represent the event
$('#mainImage').hide();     
$('#cakebox').css('background-image', "url('ajax-loader.gif')");     
var i = $('<img />').attr('src',this.href).load(function() {         
  $('#mainImage').attr('src', i.attr('src'));         
  $('#cakebox').css('background-image', 'none');         
  $('#mainImage').fadeIn();     
 });
 e.preventDefault(); //Prevent default click action which is causing the 
 return false;       //page to scroll back to the top
 });  
});


</script>

<script src="../js/s3Slider.js" type="text/javascript"></script> 

 <script type="text/javascript">

 $(document).ready(function() {
 $('#s3slider').s3Slider({
  timeOut: 4000
  });
}); 
  </script>

  <script src="../js/SpryMenuBar.js" type="text/javascript"></script>
  <link href="../root/css/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />

  </head> 


 <body>



  <div class="container">


 <div class="sprybox">
   <ul id="check_menu" class="MenuBarHorizontal">
    <li><a href="../root/index.html">Home</a></li>
    <li><a href="../root/aboutus.html" class="MenuBarItemSubmenu">About Us</a>
      <ul>
        <li><a href="../root/contactus.html">Contact</a></li>
        <li><a href="../root/news.html">News</a></li>
        <li><a href="../root/events.html">Events</a></li>
      </ul>
    </li>
       <li><a href="../root/ourmenu.html">Our Menu</a></li>
         <li><a href="gallery.html">Gallery</a></li>
          </ul>
        <div class="mainmenu">
           <a href="../root/mainmenu.html">
           <img src="../images/buttons/mainmenu.png" />
           </a>
       </div>
        <div class="backbutton">
        <a href="javascript:history.go(-1)"> 
        <img src="../images/buttons/Backbutton.png" /></a>
      </div>

    </div>  <!-- end.header --><!--end of sprybox -->

  <!--end div element -->


 <!-- thumbnails are links to the full size image -->

  <div class="cakecont">

 <div id="cakebox">

  <img src="../images/cakes/babycake1.png" alt="Main Image" id="mainImage"/>

     <div class="pageinfo2">
     <h3>Cake Type 1</h3>
     <h6>£2.00</h6>
     </div>
     <div class="infobox">
     <h6> Description </h6>
     </div> 

 <div class="gallerybox">
      <a href="../images/cakes/babycaketop.png" class="galleryicon">
      <img src="../images/thumbs/babycaketopsml.png" alt="Thumbnail 2"/></a>

      <a href="../images/cakes/babycake1.png" class="galleryicon">
      <img src="../images/thumbs/babycakesml.png" alt="Image 1"/></a>
  </div>
  </div>
</div>



 <div class="footer">
  <p>Copyright &copy; 2012 by Mark Webb. All rights reserved.</p>
 </div> <!-- end .footer -->

</div> <!-- end .container -->


 <script type="text/javascript">
 var MenuBar1 = new Spry.Widget.MenuBar("check_menu",{imgDown:"SpryAssets/SpryMenuBarDownHover.gif",   imgRight:"SpryAssets/SpryMenuBarRightHover.gif"});
  </script>

 <script type="text/javascript">

  var _gaq = _gaq || [];
 _gaq.push(['_setAccount', 'UA-29457683-1']);
  _gaq.push(['_trackPageview']);

   (function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') +    '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

 </script>


 </body>
</html>
2
  • When I visit the page, I don't see any scroll bars. The entire page fits on the screen. Are you using a smaller resolution?
    – kevin628
    Commented May 31, 2012 at 15:25
  • yes i am on a laptop so i get the scrolling effect, thanks.
    – marky
    Commented May 31, 2012 at 15:57

7 Answers 7

66

You can save the current scroll amount and then set it later:

var tempScrollTop = $(window).scrollTop();

..//Your code

$(window).scrollTop(tempScrollTop);
3
  • Thank you for your answer but i am unsure as to where i implement your code, i have little to no knowledge of Javascript.
    – marky
    Commented May 31, 2012 at 15:51
  • @user1428659: For each click, you want to save the scroll location before doing anything, and then restore it once everything has finished. Thus, you would put the first line at the beginning of your click function and the last line at the end of it (before the return statement).
    – Briguy37
    Commented May 31, 2012 at 16:05
  • @user1428659: Hmmm, I just looked at your code again and that may not work because it looks like it may be asynchronous (the fadeIn isn't called before the restore scroll). Thus, if that doesn't work for you, put the second line after the fadeIn(). On another note, if you know the height of the images, you could wrap the image tag in a blank div of that height that always displays to keep it from scrolling to begin with.
    – Briguy37
    Commented May 31, 2012 at 16:12
36

For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:

<a  
href='javascript:void(0)'  
onclick='javascript:whatever causing the page to scroll to the top'  
></a>
3
  • 2
    Thank you so much, I am trying to prevent the scroll on a $('form').submit(function{}); with e.preventDefault(); and if I put the $(window).scrollTop(tempScrollTop); before the return, or even if I returned that, it still went back up to the top. This worked for me. Commented Oct 17, 2012 at 5:05
  • 2
    @Akeel i think that by using something like href="#" the default action is applied to the browser causing it to scroll to top (redirecting to http..../#. by using what Nasser Al-Wohaibi suggested or somthing like this -Put return false; at the bottom of your click handler and the href wont be followed. -Call preventDefault on the event in your handler: function( e ) { e.preventDefault(); // your event handling code } you force the browser not to perform the default action Commented Dec 5, 2015 at 12:35
  • Excellent. I was having an issue with a SignaturePad canvas control setting my scroll position to the top when clicking a clear anchor tag. This solved my issue perfectly!
    – Mkalafut
    Commented Jul 15, 2019 at 15:10
7

Try the code below to prevent the default behaviour scrolling back to the top of the page

$(document).ready(function() {   
  $('.galleryicon').live("click", function(e) {  // the (e) represent the event
    $('#mainImage').hide();     
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");     
    var i = $('<img />').attr('src',this.href).load(function() {         
      $('#mainImage').attr('src', i.attr('src'));         
      $('#cakebox').css('background-image', 'none');         
      $('#mainImage').fadeIn();     
    });
  e.preventDefault(); //Prevent default click action which is causing the 
  return false;       //page to scroll back to the top
  });  
});

For more information on event.preventDefault() have a look here at the official documentation.

5
  • Many thanks for your answers i have implemented the code but it still jumps to the top of the page i wonder if another script is overriding it.
    – marky
    Commented May 31, 2012 at 15:49
  • I just made a test page and your solution appears to work as long as the scroll bar is not at the bottom of the page (i.e you cant scroll any further as there is no content)
    – marky
    Commented May 31, 2012 at 16:38
  • Opps hit return - However if the scroll bar is at the bottom the page jumps up 1 cm. now i have just tried adding a 400px high footer to the page an once a thumbnail is clicked the page jumps up 1cm ish but as long as don't scroll the and click another thumb the page stays static. However if you do scroll slightly again then hit a thumb the page jumps up or down depending on if you scrolled up or down - wierd. thanks for your help
    – marky
    Commented May 31, 2012 at 16:44
  • i have kind of fixed the issue at least for the time being. After inserting the e.preventDefault() i noticed that page was automatically moving to the bottom edge of the thumbnail div. To bodge the issue i extended the height of the divs containing the thumbnail to something ridiculous (400px) and now the page does not scroll when each thumb is clicked why would this work?
    – marky
    Commented May 31, 2012 at 17:59
  • Argh - now it displays a dashed box extending 400px down the page in IE, so no i have cant even bodge it...
    – marky
    Commented May 31, 2012 at 18:03
4

What you want to do is prevent the default action of the click event. To do this, you will need to modify your script like this:

$(document).ready(function() {
  $('.galleryicon').live("click", function(e) {

    $('#mainImage').hide();
    $('#cakebox').css('background-image', "url('ajax-loader.gif')");
    var i = $('<img />').attr('src',this.href).load(function() {
        $('#mainImage').attr('src', i.attr('src'));
        $('#cakebox').css('background-image', 'none');
        $('#mainImage').fadeIn();
    });
    return false; 
    e.preventDefault();
   });
 });

So, you're adding an "e" that represents the event in the line $('.galleryicon').live("click", function(e) { and you're adding the line e.preventDefault();

2
  • Thank you for your answer however as stated the code still causes the page to jump to the top - i wonder if something else is overriding the script. the demo site which uses the same code has the same effect. if you scroll down the page and then click the thumbnail the page returns to the top... thanks though.
    – marky
    Commented May 31, 2012 at 15:54
  • i have kind of fixed the issue at least for the time being. After inserting the e.preventDefault() i noticed that page was automatically moving to the bottom edge of the thumbnail div. To bodge the issue i extended the height of the divs containing the thumbnail to something ridiculous (400px) and now the page does not scroll when each thumb is clicked, why would this work?
    – marky
    Commented May 31, 2012 at 17:59
2

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

0

Something to note, when setting the scroll position, make sure you do it in the correct scope. For example, if you're using the scroll position in multiple functions, you would want to set it outside of these functions.

$(document).ready(function() {
    var tempScrollTop = $(window).scrollTop();
    function example() {
        console.log(tempScrollTop);
    };

});
0
$('html,body').animate({
  scrollTop: $('#answer-<%= @answer.id %>').offset().top - 50
}, 700);
1
  • 1
    Welcome to Stack Overflow! While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – yivi
    Commented Nov 8, 2017 at 10:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.