Enable function on another page after clicking on anchor

3

Basic example, when you click on div1 of Pagina1 open Pagina2 and change the background color, is it possible?

Page1.html

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

Page2.html

<body>
<div id="div1"></div>//body background azul
<div id="div2"></div>//body background verde
</body>
    
asked by anonymous 28.01.2016 / 00:48

2 answers

3

You can use the .hash property of the Location object for capture / check if an anchor has been reported for 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";
    }
}   
    
28.01.2016 / 01:31
0

I do not know if I understand correctly, but here it 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 I click on this 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>
    
28.01.2016 / 01:11