Gupta Keshav
Gupta Keshav

Reputation: 21

when clicked on a tag change the background color of the redirected page?

what i want to do is that when we click on anchor tag then it will go to page2.html and change the background color of a specific div.
(Anchor tag has an url&id in its href to redirect at new page but at a specific section.)
page1.html

<html>
<body>
    <a href="/page2.html#color1">yellow</a>
    <a href="/page2.html#color2">green</a>
    <a href="/page2.html#color3">blue</a>
</body>
</html>

page2.html

<html>
<body>
    <div id="color1">
        <p>yellow</p>
    </div>

    <div id="color2">
        <p>green</p>
    </div>

    <div id="color3">
        <p>blue</p>
    </div>
</body>
</html>

i tried to use fuction like
(page1.html)

    <a href="/page2.html#color1" onclick="changecolor()">yellow</a>
    <script>
        function changecolor() {
            document.getElementById(color1).style.background = "yellow";
        }
    </script>

i tried more fuction like this but none of them works!
is it possible to do it by only using javascript??
can anyone help me??

Upvotes: 2

Views: 739

Answers (2)

Max Svidlo
Max Svidlo

Reputation: 774

I think its better to listen to the hashchange event, and then just manipulate the needed elements css

<body id="someId">
    <a href="./page2.html#yellow">yellow</a>
    <a href="./page2.html#green">green</a>
    <a href="./page2.html#blue">blue</a>
</body>

<script>
window.addEventListener('hashchange', (event) => {
    const color = window.location.hash.replace('#', '')
    document.getElementById('someId').style.background = color
});
</script>

Upvotes: 0

tacoshy
tacoshy

Reputation: 13012

IMHO the best solution should be not to use an onclick event as it does not trigger the script to change styles on another site that isn't even loaded yet.

As such I would recommend to run the script on the 2nd Page and use window.location.href to get the url.

Then you can use Switch-Statements to apply changes something like this:

var url = window.location.href,
    div = document.getElementById('id');

switch (url) {
  case /page2.html#color1:
    div.style.background = "yellow";
    break;
  case /page2.html#color2:
    div.style.background = "green";
    break;
  case /page2.html#color3:
    div.style.background = "blue";
    break;
}

Upvotes: 0

Related Questions