IvanN
IvanN

Reputation: 327

Visited JS links in chrome

I'm having a bit of a trouble with Chrome a:visited links colors when reference is in JS:

<a href='javascript:openPage("p1", "p2");'>Link to a page with p1 and p2</a>

JS behind the scene is something like:

this.openPage = function (p1, p2) {
    var url = "MyPage.aspx";
    url += "?Parameter1=" + p1;
    url += "&Parameter2=" + p2;
    window.open(url);
}

Other browsers I'd tested with (IE, Firefox, Edge), change the color of the link once it was clicked, even without explicitly writing CSS for it. But Chrome stays still and holds it's positions.

I know about the security issues and that a:visited functionality is very limited, but I don't look for anything fancy, just changing color of the text, something you'd expect to happen but doesn't. Adding CSS won't help

a
{
    text-decoration: none;
}
a:visited 
{
    text-decoration: none;
    color: #551A8B;
}

Direct page links work fine.

I could work around with adding

onclick="this.style.color='#551A8B';"

but that would be quite a challenge to change all the links in the app. Any help will be much appreciated.

Upvotes: 0

Views: 1132

Answers (2)

Marie
Marie

Reputation: 2217

If you wanted your links to show clicked when they were clicked and avoid any issues you may run into because of javascript in the href you could try something like this

function doLink() {
  var p1 = this.getAttribute("data-p1");
  var p2 = this.getAttribute("data-p2");
  
  var url = "MyPage.aspx";
  url += "?Parameter1=" + p1;
  url += "&Parameter2=" + p2;
  alert(url)
}

var links = document.getElementsByClassName("color-change-links");

var link;
for (var i = 0; i < links.length; i += 1) {
  link = links[i];
  
  var p1 = link.getAttribute("data-p1");
  var p2 = link.getAttribute("data-p2");
  
  link.href = "#" + p1 + p2;
  link.onclick = doLink;
}
<a href="#" class="color-change-links" data-p1="link11" data-p2="link12">Link to a page with p1 and p2</a><br />
<a href="#" class="color-change-links" data-p1="link21" data-p2="link22">Link to a page with p1 and p2</a><br />
<a href="#" class="color-change-links" data-p1="link31" data-p2="link32">Link to a page with p1 and p2</a><br />
<a href="#" class="color-change-links" data-p1="link41" data-p2="link42">Link to a page with p1 and p2</a>

Upvotes: 1

Ji_in_coding
Ji_in_coding

Reputation: 1701

I agree with toni's comment. You should use onclick to trigger your function. also add a invalid href on your link to make it unvisited to begin with. Upon clicking, it will become visited.

<a href='#' onclick="openPage('param1', 'param2')">Link to a page with p1 and p2</a>

see it in code pen.

Upvotes: 0

Related Questions