I've seen a few questions on here related to this, but I'm not seeing the exact situation I'm talking about so I figured I'd ask.
I have a page with two divs. A sidenav div ( sidediv
) and a main body ( maindiv
) div.
What I want: To click a link in the side nav to load a page in the main div. At the moment, anyway, it's always the same page, but it's a huge page with several anchors. The items in the side link to varied anchors.
What I'm doing: My sidenav links look like so:
<a href="#" onclick="loadPage('mypage.html#ds'); return false;">Desired Section</a>
and the JS:
function loadPage(url){
var xhr= new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return;
document.getElementById('maindiv').innerHTML= this.responseText;
};
xhr.send();
}
What happens: It loads mypage.html just fine, but refuses to go to the anchor.
How do I make that happen (sans jQuery, BTW, I currently am not using it on site and don't feel like loading it in for one thing)
Thanks.
Ok this was interesting so I took a shot at it for you. Here is what I came up with. It uses scrollIntoView
. Also keep in mind that I simulated the ajax call so my loadPage
function does some stuff differently than you will.
var pages = { 'mypage.html': '<div id="ts" class="page">my stuff</div><div id="ds" class="page">my more stuff</div><div id="eds" class="page">my even more stuff</div>', 'yourpage.html': '<div id="ts" class="page">your stuff</div><div id="ds" class="page">your more stuff</div><div id="eds" class="page">your even more stuff</div>' }; function loadPage(url) { var set = url.split('#'), page = set[0], id = set[1]; // simulate xhr request setTimeout(function() { document.getElementById('maindiv').innerHTML = pages[page]; document.getElementById(id).scrollIntoView(); }, 1000); }
.page { height: 400px; } .menu { width: 200px; float: left; position: fixed; } #maindiv { width: 50px; float: right; background: lightblue; }
<div class="menu"> <a href="#" onclick="loadPage('mypage.html#ds'); return false;">My Page #ds</a><br /> <a href="#" onclick="loadPage('yourpage.html#eds'); return false;">Your Page #eds</a> </div> <div id="maindiv"> </div>
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.