Skip to content Skip to sidebar Skip to footer

Updating Visited Status Of A Link When Changing Its Href Attribute, Under Chrome

When I am updating links with JavaScript $('#link_id').attr('href', some_new_url) the color theme for visited/non-visited links persists, regardless of the status of the new url a

Solution 1:

Definitive answer

What you could do to fix this, is simply forcing the browser to recalculate the styles by completely removing the href attribute, and then re-adding it back again immediately afterwards. That will make the browser first calculate the styles, since the <a> is no longer a link without the href, and then you add the href you want to give it. The code would then be:

$('#link_id').removeAttr('href').prop('href', some_new_url);

Demo

PS: in this case, using .attr('href', some_new_url); would probably work equally fine.

Previous attempts

What I'm thinking is that this is a rendering glitch. It doesn't recalculate the styles when the :visited state changes because of the script. This minimal example of your problem shows this well. What you could try is either of the following:

Using the element's properties

What the problem might be is that you're changing the attribute, which in turn changes the href property. If you directly change the href property it might work. You can do this via jQuery.prop, which would use the following code to change the link:

$('#link_id').prop('href', some_new_url);

Demo. I don't really have very high hopes about this one, but it's worth trying. What I do suspect will work much better is:

Forcing to recalculate the styles

If you want to force a recalculation of the styles, you can simply change a class on the highest element you want updated. Since you're updating the <a> element alone, you'd need something like this:

$('#link_id').prop('href', some_new_url).toggleClass('webkit-force-recalculate');

Demo

I think that is quite likely to do the trick.


If neither of these approaches work for you, you could of course use maximgladkov's solution.

Solution 2:

You can change it like this:

$('#link_id').replaceWith($('<a href="' + some_new_url +'">' + $('#link_id').text() + '</a>'));

It should do the trick. Tested: http://jsfiddle.net/maximgladkov/L3LMd/

Solution 3:

Frequently experience similar issues, e.g. when setting size of elements with border, there are stray borders left etc.

Though this is not directly the same, I have found that hiding the element does the trick. Have not had any trouble with it.

Simple fiddle

$("#change_link").on("click", function(e) {
    $("#anchor1").hide();
    $("#anchor1").attr('href', $("#url").val());
    $("#anchor1").show();
});

This should force a redraw of the element.

Solution 4:

I think what you might be looking for is the following CSS code:

a:link {
    text-decoration: none;
    color: #00F;
}
a:visited {
    color: #00F;
}

Post a Comment for "Updating Visited Status Of A Link When Changing Its Href Attribute, Under Chrome"