I'd like to add a CSS class to HTML bookmarks generated by core. Examples of these bookmarks include:

<a id="new"></a>

<a id="comment-766013"></a>

I'd like to turn them into:

<a id="new" class="bookmark"></a>

<a id="comment-766013" class="bookmark"></a>

I'm unable to alter these in comment.tpl.php and it looks like theme_comment_view is unavailable in D7, so I'm kind of lost.

Background: I have a sticky header menu that's 60px tall and as such, HTML bookmarks are landing about 60px lower on the page than they should. An example of this is when you link to comment by ID, like http://site.com/article#comment-766013.



Those anchors are added in comment_view(). To override them you'll need to implement hook_comment_view_alter() and reproduce a bit of the logic from the original view function:

function MYMODULE_comment_view_alter(&$build) {
  $comment = $build['#comment'];
  $node = $build['#node'];

  if (empty($comment->in_preview)) {
    $prefix = '';
    $is_threaded = isset($comment->divs) && variable_get('comment_default_mode_' . $node->type, COMMENT_MODE_THREADED) == COMMENT_MODE_THREADED;

    // Add 'new' anchor if needed.
    if (!empty($comment->first_new)) {
      $prefix .= "<a id=\"new\" class=\"bookmark\"></a>\n";

    // Add indentation div or close open divs as needed.
    if ($is_threaded) {
      $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';

    // Add anchor for each comment.
    $prefix .= "<a id=\"comment-$comment->cid\" class=\"bookmark\"></a>\n";
    $build['#prefix'] = $prefix;
|improve this answer|||||

i would prefer using drupal.behaviors which allows you to add class and add css anytime. what it does is whenever you include anything in drupal.behaviors it will apply for every event that happens in your drupal page even on ajax event. using traditional js won't allow you to do it.



Drupal.behaviors.makeMeSmelly = {
  attach: function (context, settings) {
    // This will only get ran once
    context.once(function() {
     $('h1', this).addClass('.the-original-smelly-bean');

    // This get's ran on every request
|improve this answer|||||
  • Good to know. Thanks – and makeMeSmelly is a fantastic name for a method! – DeepFriedBits Apr 18 '14 at 21:05

add js file and write code for D7

(function($) {





|improve this answer|||||
  • I'd prefer to make the change on the server because it's the CSS needs to kick in as soon as possible (onload, as opposed to after onready). Further, I'd have to write a JS regex for your second case because I need to apply this class to every comment ID bookmark, not just the ID given in this example. – DeepFriedBits Apr 18 '14 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.