Load another html doc instead of the current one using pure Javascript

Asked

Viewed 142 times

1

In this work of the facul, estu making an app with several menus, if I do everything in a single html, will get huge file. So by clicking the options on a given menu, I would like to continue running the app with another html document, loaded instead of the current one. I could do with html with something like: < a href..... /> right?

But I would like to do this within a javascript function, which is triggered by clicking a button on a menu. Follow the snippet of my code:

    <div class="menu" id="menuCorNaoCor" style="display:none">
            <div class="centralizar">
                <button class="botao" onClick="carregarMenuCorrentista()"> Correntista </button>
                <button class="botao" > Não Correntista </button>
            </div>
    </div>

<script>
        function carregarMenuCorrentista(){
          //Carrega o menu, que está em outro documento html
        }

</script>
  • I will load it centered, in the middle of the page, instead of the current one. I have a css file that does this formatting for menus already. The point is just that I didn’t want to put this menu in the same doc html, which is already getting big.

  • 1

    Yes, you want to load content from another page into the <div class="centralizar">?

  • It is, in a way. But this, only at the click of the Merchant button for example.

  • I’ll edit the question so you can see how it looks... it’s much better to do this, because you’ll have to use ajax

  • :Can you do it with ajax? I haven’t seen it yet.

  • If you don’t want to leave the current page and just upload content from another page, the best is Ajax.

  • This last option

  • So you don’t even need function, just put onclick="location.href='pagina.html'";

  • No. I got confused. kkk. I didn’t want to have to load another page.

  • From what I understand, you want to make a layout and when opening a link from the menu, upload the content of the link within the page itself, without having to copy the entire layout on each page of your site/app, right? If yes, I can answer your question with an ajax solution, as mentioned by @dvd.

Show 5 more comments

1 answer

0


Put this Ajax in pure JS function, replacing pagina.html by the page you want to load. This will replace the full page with the return of Ajax:

if(navigator.appName == "Microsoft Internet Explorer"){
    var http = new ActiveXObject("Microsoft.XMLHTTP");
}else{
    var http = new XMLHttpRequest();
}

var url_ = "pagina.html";
http.open("GET", url_, true);
http.onreadystatechange = function(){
   if(http.readyState == 4){
      document.querySelector("html").innerHTML = http.responseText;
   }
}
http.send(null);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.