Anuya
Anuya

Reputation: 8350

Highlighting Hyperlink which is clicked

I have a datalist in my webpage which dynamically loads hyperlinks on it. On clicking hyperlink, the corresponding content will be loaded on the same page Since loading the content happens after a page refresh, it is challenging to highlight the clicked hyperlink.

I want to show users which content they are reading, by highlighting the hyperlink they clicked.

I tried it using css, but since there is page refresh to load the content, it is not mainitaining the highlighted color.

How can i achieve this ?

Upvotes: 0

Views: 342

Answers (1)

Rob Sobers
Rob Sobers

Reputation: 21125

If you're triggering a full page refresh, you're losing the state of the currently loaded page. There are a few options which boil down to: 1.) don't refresh the page when the user clicks, 2.) save the state.

Option #1

Don't trigger a page refresh when the user clicks the link. Instead, get the content from the server via an AJAX call.

For example, if you're using jQuery as your AJAX library you can set a click handler on all of your links. When one is clicked, the handler will trigger and you can then grab the content via AJAX and add a class to the clicked link. Your CSS can contain a rule to color it differently.

$("a").click(function () {
  var clicked = $(this);
  // get the content from the server
  $.get('ajax/test.html', function(data) {
    // drop the content into the page
    $('.result').html(data);
    // flag the link as clicked
    clicked.addClass('clicked');
  });      
});

Option #2

Store the mapping of which users clicked which links in a database table on the server. Whenever a page is requested and you're rendering the HTML, you can add a CSS class to the links you know have been clicked so they can be represented as a different color when the browser loads the page.

Upvotes: 1

Related Questions