What is the (best) way to make a div clickable using a render array in code?

I am creating a module that outputs a title in a rounded box, so I use the markup type and specify a class with #prefix and #suffix and apply some css on that class. This gets me a box, but I want to make the box clickable with a different url for each box. What would be a good way to do this?

I could put an onclick in the prefix or put in the prefix and in the suffix. But both are not very pretty.

I'm using Drupal 7 and would like not to use additional modules like views.

  • I take it you are creating a link here?
    – Alex Gill
    Oct 8, 2012 at 15:41
  • Yes, the divs should be links.
    – Whiskey
    Oct 8, 2012 at 18:08

2 Answers 2


It sounds like you want to create an Accordion, I would look at Views Accordion because it sounds like what you want. I would try to stay away from custom javascript and html and attempt to theme views_accordion as you want it to look.

  • Thanks. I put some additional info in the question. I want to do this in code.
    – Whiskey
    Oct 8, 2012 at 18:11

I did some more digging and came across the container type. This is imo the best way to achieve this.

You use a container as wrapper to which you assign the class and onclick attributes. Then with markup you put whatever you want inside the container/div. It is possible to put more items in the container simply by adding more children to the $divwrapper class.

This is the code I ended up with (for several titles/boxes):

  $titles = array(1 => 'title 1', 2 => 'title 2', 3 => 'title 3');
  $output = array();
    foreach ($titles as $id => $title) {
      $onclick = "location.href='/node/{$id}'";
      $divwrapper = array(
          '#type' => 'container',
          '#attributes' => array('class' => array('rounded_box'), 'onclick' => $onclick)
      $divwrapper["box_{$id}"] = array('#markup' => "<p>{$title}</p>");
      $output[] = $divwrapper;
  return $output;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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