Activate function on another page after clicking anchor

Asked

Viewed 555 times

3

Basic example, by clicking on div1 of Pagina1 open the Pagina2 and change the background color, this is possible?

Pagina1.html

<body>
<div>
<a href="Pagina2.html#div1"  class="">div1</a>
<a href="Pagina2.html#div2"  class="">div2</a>
</div>
</body>

Pagina2.html

<body>
<div id="div1"></div>//body background azul
<div id="div2"></div>//body background verde
</body>

2 answers

3


You can use the property .hash of the object Location, to capture/check if any anchor has been reported to the second page:

Use the script in Pagina2:

if(window.location.hash) {
    var hash = window.location.hash;
    alterarCor(hash);
}

function alterarCor(ancora) {
    if (ancora == "#div1") {
        document.body.style.backgroundColor = "blue";
    } else if (ancora == "#div2") {
        document.body.style.backgroundColor = "green";
    }
}   

0

I don’t know if I got it right, but here goes:

01.html:

<body>
    <div>
        <a href="02.html?div=1"  id="d1">Cor1</a>
        <a href="02.html?div=2"  id="d2">Cor2</a>
    </div>
</body>

<script>
    var url   = window.location.search.replace("?", ""); //pega url
    var itens = url.split("&"); //pega meus parâmetros (div=1 ou div=2)
    var valor = itens[0].slice(4); // retira 4 c. pois div= tem 4 caracteres
    if(valor == 1)
    {
        document.bgColor = "yellow";  // se for Cor 1 muda para amarelo
    }
    else if(valor == 2)
    {
        document.bgColor = "red";   // se for Cor 2 muda para vermelho
    }
</script>

02.html:

<body>
    <div>
        <a href="01.html?div=1"  id="d1">Cor1</a>
        <a href="01.html?div=2"  id="d2">Cor2</a>
    </div>
</body>

<script>
    var url   = window.location.search.replace("?", ""); //pega url
    var itens = url.split("&"); //pega meus parâmetros (div=1 ou div=2)
    var valor = itens[0].slice(4); // retira 4 c. pois div= tem 4 caracteres
    if(valor == 1)
    {
        document.bgColor = "blue";  // se for Cor 1 muda para azul
    }
    else if(valor == 2)
    {
        document.bgColor = "green";  // se for Cor 2 muda para verde
    }
</script>

On the same page:

I made this example on the same page, if you click on such link it changes the color:

<body>
    <div>
        <a href="this.html?div=1"  id="d1">Cor1</a>
        <a href="this.html?div=2"  id="d2">Cor2</a>
    </div>
</body>

<script>
    var url   = window.location.search.replace("?", "");
    var itens = url.split("&");
    var valor = itens[0].slice(4); // 5 pois nome= tem 5 caracteres
    if(valor == 1)
    {
        document.bgColor = "blue"; 
    }
    else if(valor == 2)
    {
        document.bgColor = "green"; 
    }
</script>

Browser other questions tagged

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