Cattarina
Cattarina

Reputation: 61

Redirect to hash url using Jquery

I've seen site redirection within a certain delay/time limit however is it possible to do that within a page that only has hash urls?

What is the code for redirecting a hash location within a page? For instance we are currently in #home then when I click on #load, it waits 5 seconds then redirects to #about - all within just one page just different hashes/#.

Thank you!

Upvotes: 2

Views: 11196

Answers (2)

Zenit
Zenit

Reputation: 475

As simple as this

$(location).attr('href', 'index.php');
window.location.hash = "#about";
location.reload();

  1. Select the location where you want to go
  2. Specify to the location in which part of the website you want to go
  3. Reload the website in order to make work the hash function.

Upvotes: 8

plalx
plalx

Reputation: 43728

Well, if you click on an anchor already associated with another hash (would be curious, but this is what I understood), you will first have to prevent the defautl behavior, then you can redirect.

Assumed HTML

<a href="#load">some link</a>

JS (once document is ready)

$('a[href="#load"]').click(function (e) {
    e.preventDefault();

    setTimeout(function () {
        window.location.hash = 'about';
    }, 5000);

});

EDIT: "going to the #load will automatically redirect with a delay of 5 seconds without clicking"

$(window).on('hashchange', function () {
    if (window.location.hash == '#load') {
        setTimeout(function () {
            window.location.hash = 'about';
        }, 5000);
    }
});

Upvotes: 6

Related Questions