简体   繁体   中英

jQuery unwanted scroll up

I have a bunch of description blocks that are supposed to fade in when the corresponding image is clicked, fading out the previous one. Fading is working, but the page keeps scrolling up on each click, messing with the user's navigation.

google.load("jquery", "1.3");
google.setOnLoadCallback(function() {
jQuery(function($) {

   $('#a').click(function(e){    
        $('#bio-b,#bio-c').fadeOut('slow', function(){
            $('#bio-a').fadeIn('slow');
        });
    });
});
});

I am a JavaScript/jQuery noob and mostly pieced this together from code found online. I hope the code is not all backwards.

edit: this is the HTML for image that would be clicked in this case :

<a href="#" id="a"><img></a>

description:

<article id="bio-a" class="bio"></article>

and the CSS (the description isn't displayed on loading the page)

#bio-a {
    display : none;
}

Any thoughts on what's causing this, how to fix it?

Using an href of # effectively means to look for an element with an id of nothing. Obviously you do not have that. To fix the link of being 'followed' you need to call preventDefault on the event that gets passed to your handle.

Ie:

$('#a').click(function(e){    
    $('#bio-b,#bio-c').fadeOut('slow', function(){
        $('#bio-a').fadeIn('slow');
    });
    e.preventDefault();
});

Try removing the href="#" attribute from the link, that might trigger a page scroll. This behaviour is not defined per se in the HTML standard, <a href="#"> basically just points to a relative source and it's up to the browser vendor to implement the behaviour (some browsers may even reload the page). Most developers tend to use those elements because their either to lazy to set cursor: pointer on the element or have some legacy onclick handlers…

And do yourself a favor and use the latest possible version of jQuery (1.10 or 2.0, but don't forget to read the disclaimer for jQuery 2.0 before upgrading). ;-)

I believe this is what you are looking for. If I understood you incorrectly please let me know and I'll adjust my answer :

$(document).ready(function(){

 $('.image').click(function(){    
   var findIdNumber = $(this).attr("id");
   $('#bio-' + findIdNumber).fadeIn();
   $("article").not('#bio-'+findIdNumber).fadeOut();     
  });
});

JSFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM