73

What I am attempting to do is to highlight a div with a certain id, when It has been referred to by an anchor on another page IE:

User clicks link href="qw.html#test", when the page is loaded, then the div with the id="test" is highlighted so that the user can see it clearly.

I'm sure that I've seen a CSS3 example where a div is highlighted if it was linked to. Or was it JavaScript?

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
harley_woop
  • 1,629
  • 4
  • 15
  • 28

3 Answers3

140

You need to use the :target pseudo-class:

:target {
   background-color: #ffa;
}

JS Fiddle demo.

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
David Thomas
  • 240,457
  • 50
  • 366
  • 401
  • 2
    @DavidThomas, can this be done for *any* target? Or do I have to specify the id each time? – DAE Mar 12 '18 at 12:41
  • @DAE: the 'target' is identified by the URL fragment identifier (the `#elementID`), so it can only work for an element that has an `id` and has its `id` in the URL like so: `http://example.com#elementID` – David Thomas Mar 12 '18 at 13:56
  • 1
    @DavidThomas actually in the end i tried a:target and it works fine for my purposes :) – DAE Mar 13 '18 at 12:43
  • If answer was self contained, then it would be worth an up vote. As is it misses the important part: how to create a target is only on the other site. – ctrl-alt-delor May 30 '22 at 07:05
0

JavaScript can be used to dynamically add/change the class of the div:

If you have:

<div id="test"></div>

Javascript function, executed by the click of the anchor:

document.getElementById("test").className += " highlighted";

Result:

<div id="test" class=" highlighted"></div>
HoldOffHunger
  • 15,349
  • 8
  • 79
  • 115
blearn
  • 1,198
  • 10
  • 17
0

You can do this in JavaScript. Refer to How to get the anchor from the URL using jQuery? on how to get the anchor from URL and then it can be something simple like

document.getElementById(hash).style.backgroundColor="Yellow";
Community
  • 1
  • 1
Yuriy Galanter
  • 36,794
  • 12
  • 65
  • 122