简体   繁体   中英

jQuery fadeIn making page scroll to top / jump

jQuery is destroying me this week. I'm using fadeIn via jQuery on my portfolio site ( http://www.codeisdna.com ) to open up a section once it's clicked. Here's the HTML code I'm using:

<div class="project first project_name">
    <div class="title">
        Project Title!
        <div class="date">2012</div>
    </div>
    <a class="expand" title="Click to expand the project." href="#project_1">Project Title!</a>
</div>

Which opens up a tab:

<div id="project_1" class="project_full pname"></div>

Using this js:

    $(document).ready(function(){
        $(".project").click(function() {
            $("a.expand").removeClass("hovered");
            $(this).find("a.expand").addClass("hovered");
            $(".project_full").hide();
            var selected_tab = $(this).find("a").attr("href");
            $(selected_tab).fadeIn();
            return false;
        });
    });

EDIT : Here is the CSS code for .project_full (the expanded tab -- the CSS code for .project is irrelevant):

.project_full {
    display: none;
    margin-top: 20px;
    width: 100%;
    max-height: 450px;
    padding: 20px 0px;
    text-align: center;
    background: url(../img/code.jpg) top center no-repeat fixed #293134;
    box-shadow: inset 0 0 10px rgba(0,0,0,0.5);
    color: #fff;
    overflow: hidden;}
.project_full .wrapper {position: relative;}

I've tried assigning a fixed height to a parent div, e.PreventDefault() doesn't work (I'm using anchor based tabs, so nothing of that sort will work), and so on. The page jumps on the first click and with each successive click. I know it jumps due to the missing content once the div is unhidden and "rehidden."

I'm wondering if HTML5 data attributes would remedy this? But then again, why would it as the anchor would still exist, albeit it being blank (#).

Hopefully someone with a lot more JS experience can help me!

Either change your handler adding preventDefault

    $(".project").click(function(e) {
        e.preventDefault();
        $("a.expand").removeClass("hovered");
        $(this).find("a.expand").addClass("hovered");
        $(".project_full").hide();
        var selected_tab = $(this).find("a").attr("href");
        $(selected_tab).fadeIn();
        return false;
    });

Or change your a tag href attribute to be something like 'javascript:'

Or replace a tag with say span and let your click handler remain unchanged.

Or add name attribute to a tag ( <a name='project_1'></a> ) in right place as it is scrolling to this tag or beginning of the page as there is no ancor with corresponding name

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