开发者

Display DIV and then go to an element inside that DIV

I am currently trying to unhide a DIV and then right after scroll down to an element.

I have this "index" of text where I have a list of anchor tags href'ing to different ID's down the page, but at first sight the text is hidden and will first display when you click on one of the index links. All this works fine untill I get to the scroll part.

There is nothing special about the code so far, it's just a mere if statement adding & removing a CSS class depending on the client action. But how do I get the page to automatically scroll down after the DIV displays?

I tried this solution: How to go to specific to element on page, but I couldn't seem to fit it in my own script.

if ($('#<%=paragraph.ClientID%>').hasClass("readable")) {
     $('#<%=paragraph.ClientID%>').removeClass("readable"); // Readable is the class that hides the paragraphs.
     // Run function to scroll down to se开发者_StackOverflow社区lected element here.
}
else {
     $('#<%=paragraph.ClientID%>').addClass("readable");
}

What I first tried was something like this:

(function($) {
        $.fn.goTo = function() {
            $('html, body').animate({
                scrollTop: $(this).offset().top + 'px'
            }, 'fast');
            return this; // for chaining...
        }
    })(jQuery);

    function showParagraphs(elementId) {
        if ($('#<%=paragraph.ClientID%>').hasClass("readable")) {
            $('#<%=paragraph.ClientID%>').removeClass("readable");
            scrollToElement(elementId);
        }
        else {
            $('#<%=paragraph.ClientID%>').addClass("readable");
        }
    };

    function scrollToElement(elementId) {
        $(elementId).goTo();
    };

But the above script didn't work. And my javascript skills a limited, so I'm kind of lost.

Any hints or help would be awesome. Thank you.


Your code looks mostly working. I think the only thing you need to change is that in your showParagraphs function you just have to...

replace scrollToElement(elementId) with scrollToElement('#<%=paragraph.ClientID%>')

...since you're pulling the id for the element you want to affect from the server and not a passed in argument.


If that doesn't do it, here's a working demo that I threw together that you can try implementing as an alternative.


If I understand your problem right, it's an easy solution. To wait for the event to finish, use callback function.

Example code:

$('.clickable').onclick(function(){
   $('.mydiv').show('slow', function(){
     location.href = '#myElement';
   });
});

And link to jQuery.show() docs

Oh, maybe it's confusing ... '.clickable' is your action trigger (a button, link), '.mydiv' is your div that shows up, #myElement is the id of element you want to scroll to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜