ASP.NET navigate to anchor in code behind

核能气质少年 提交于 2019-12-05 22:12:45

I've solved my problem. JavaScript code was called before my anchor even existed. That's why Firefox wasn't scroll page down.

My code looks now like tihs:

this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "window.onload = function() {window.location.hash='#message';}",
                                         true);

After page load I'm calling my simple JavaScript function.

The key to found solution was Cleiton answer. Firebug reports that getElementById was returning null reference. Then I looked at generated HTML like andrewWinn suggested - JavaScript was called before anchor existed. Made little googling and found solution.

Thanks for your answers!

Mendoza, you can use native scrollIntoView function.

To do what you want, just write:

this.ClientScript.RegisterStartupScript(this.GetType(),
                                        "navigate",
                                        "document.getElementById('id_of_the_element').scrollIntoView();",
                                        true);

I ran into this once. Have you taken a look at the actual HTML? If I remember, FireFox was being case sensative on the anchors. I don't know if that changed recently or not.

You could try using the jQuery LocalScroll plugin. Using this, you could scroll using:

$(function() {
    $.scrollTo("#message");
});

Or with your ASP.NET code:

protected void ButtonSend_Click(object sender, EventArgs e)
{
    this.ClientScript.RegisterStartupScript(this.GetType(),
                                            "navigate",
                                            "$(function() { $.scrollTo('#message'); });",
                                             true);
}

It's not an ideal solution, especially if you're not using jQuery anywhere in your project already, but it might solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!