Skip to content
Advertisement

how to hide/show element according to url parameter

i have 4 url parameters like so

http://127.0.0.1:4000/post?&id=5f04698e6114e4069099d8bf#like
http://127.0.0.1:4000/post?&id=5f04698e6114e4069099d8bf#comment
http://127.0.0.1:4000/post?&id=5f04698e6114e4069099d8bf#share
http://127.0.0.1:4000/post?&id=5f04698e6114e4069099d8bf#save

and 4 divs like html

<div id='like' class='hide'></div>
<div id='comment' class='hide'></div>
<div id='share' class='hide'></div>
<div id='save' class='hide'></div>

and css

.hide{
    display:none;
    }

how do i unhide elements when a url param is searched, for example if i search for

http://127.0.0.1:4000/post?&id=5f04698e6114e4069099d8bf#like

the div with id='like should be now visible

what i have tried i have tried to unhide the elements on button click, and I am successful using classList.toggle('hide') but how do I achieve the same thing with changes in url. I would be best if the classList is set acc to the url for example when there is #like in url ,the element with id like should not contain the class hide anymore. other answers are also accepted ,thanks.

Advertisement

Answer

No JavaScript needed. Use the CSS :target selector like:

#like.hide:target {display:block;}

.hide {
  display: none;
}

#like.hide:target,
#comment.hide:target,
#share.hide:target,
#save.hide:target {
  display: block;
}
<div id='like' class='hide'>like</div>
<div id='comment' class='hide'>comment</div>
<div id='share' class='hide'>share</div>
<div id='save' class='hide'>save</div>

<a href="#like">like</a>
<a href="#comment">comment</a>
<a href="#share">share</a>
<a href="#save">save</a>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement