Skip to content
Advertisement

href / anchor (jump to id) weird behavior in Github pages

Please take a look at my page, https://kuncung38.github.io/portfolio-website/

When I used live server from VSCode, everything works just as expected, When I uploaded this to github pages, a weird bug appeared.

You will notice the problem, it has a weird behavior when you clicked either button, you will have to clicked the button twice for something to happen. Here is my code:

var x = document.getElementById('second-section');
var memeSection = document.getElementsByClassName("memeSection");
var seriousSection = document.getElementsByClassName("seriousSection");
var meme = document.getElementsByClassName("meme");
var serious = document.getElementsByClassName("serious");

function show() {
    x.style.display = 'block';

    Array.from(memeSection).forEach(memeSection => memeSection.style.display = 'none');
    Array.from(seriousSection).forEach(seriousSection => seriousSection.style.display = 'block');
    Array.from(meme).forEach(meme => meme.style.display = 'none');
    Array.from(serious).forEach(serious => serious.style.display = 'flex');
    window.location.href = "index.html#home";
  }

function showMeme() {
    x.style.display = 'block';

    Array.from(memeSection).forEach(memeSection => memeSection.style.display = 'block');
    Array.from(seriousSection).forEach(seriousSection => seriousSection.style.display = 'none');
    Array.from(meme).forEach(meme => meme.style.display = 'flex');
    Array.from(serious).forEach(serious => serious.style.display = 'none');
    console.log("no problem till here")
    window.location.href = "index.html#home-meme";
}

Basically the two buttons on the homepage have these two functions. I do not know what is wrong with my codes, You can inspect the webpage to see the full code if needed, or you can click here.

Please help me 🙁

Advertisement

Answer

The first time you click, index.html is added to the URL, so effectively you navigate away from the current page. If you start out at https://kuncung38.github.io/portfolio-website/index.html the problem disappears.

A solution would be not to overwrite the entire window.location.href but only the hash:

window.location.hash = "#home";

That should work whether or not index.html is in the URL.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement