AndrewK
AndrewK

Reputation: 29

Javascript to highlight current page

New javascript user here... thanks in advance for any help. I am adding pagination to a news site so only 10 articles show on page 1 and you have to select 2, 3, 4, etc. to see more articles. The code I have allows me to go to page 2, 3, etc., but it is not highlighting my active page for some reason.

Here is the code I have:

HTML:

<table class="news-pages" id="paginator">
 <tr>
   <% for(var i = 1; i <= num_pages; i++) { %>
     <td class="news-pages-option"><%-i%></td>
   <% } %>
  </tr>
</table>

JS:

function getParameterByName(name, url) {
  if (!url) url = window.location.href;
  name = name.replace(/[\[\]]/g, "\\$&");
  var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
      results = regex.exec(url);
  if (!results) return null;
  if (!results[2]) return '';
  return decodeURIComponent(results[2].replace(/\+/g, " "));
}

const page = getParameterByName('p');
$('.news-pages-option').parent().addClass('active');

CSS:

.news-pages-option.active {
  background-color: #cccccc;
  border: none;
  padding: 3px 8px 3px 8px;
  text-decoration: underline;
}

Upvotes: 0

Views: 138

Answers (1)

James
James

Reputation: 22246

It looks like you want to highlight the tab corresponding to the page variable extracted from the url. Try:

const page = getParameterByName('p') - 1; // the array of tabs is zero-based so subtract one
$('.news-pages-option:eq(' + page + ')').addClass('active');

Upvotes: 1

Related Questions