-1

i'm quite new when it comes to programming, so i do have some basic issues. one of them, that i can't really solve is the following:

i wrote a javascript code to change a div's content on a button click. it works fine, but only on the second click.

the buttons html:

 <li class="navli"><a class="navbutton" id="home" onclick="navClick(this.id)">Home</a></li>

the javascript:

var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
        })
        .then(function(data){
            contentText = data;
        })
        document.getElementById("content").innerHTML = contentText;
}

1 Answers1

0

It looks like an async mishap. Try it like this:

var buttonId = "";
var contentText = "";

function navClick(clicked_id)
{
    buttonId = clicked_id;
    changeContent();
}

function changeContent(){
    fetch("./pages/"+buttonId+".txt")
    .then(function(response){
        return response.text()
    })
    .then(function(data){
        contentText = data;
        document.getElementById("content").innerHTML = contentText;
    })
}

The innerHMTML needs to be updated inside the then, otherwise it will probably run before the fetch completes. My best guess.

igg
  • 2,172
  • 3
  • 10
  • 33