0

I created a block through drupal hook_block_info (and hook_block_view, but this doesn't really matter)

function mymodule_block_info() {
  $blocks['menu_mobile'] = array(
    'info' => t('Mobile Menu'),
    );
  return $blocks;
}

I need it to be hidden initially and then to show on webpage resize/mobile. I did this by applying a display:none to css and the media rule

@media screen and (max-width: 768px)

It works. Almost Perfectly. The problem is that, at the very beginning of webpage loading, the block is visible and, for maybe a second, it shows on its webpage, then the display:none does its work hiding it. It is annoying. I saw here some properties of the array to be returned by the hook, but none really fits my case. For example, enabling/disabling hides the block, but i don't really know how or when to show it again.

https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_info/7

So, how i can have the block initially hidden, or fasten the display:none (that is contained in the style.css of my custom theme)?

1

A block can have a content element when created in code. This content element can be raw HTML or a drupal render array. If you use raw HTML for your block you can just put <style type="text/css">#your-block-id { display: none;}</style> directly into your block output.

Or if you use a render array you can do something similar with the #attached key on the render array. This is outlined in the API usage of drupal.org and a comment provides an example:

$block['content'] = array(
  '#markup' => mymodule_testblock_content(),
  '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'mymodule') . '/css/mymodule.css',
      ),
      'js' => array(
        drupal_get_path('module', 'mymodule') . '/js/mymodule.js',
    ),
  ),
);

Obviously the render array approach is a cleaner, more elegant solution. You can even have the CSS inline when using #attached.

| improve this answer | |
  • Good solutions! Unfortunately, yet too slow and the issue is still there. – Sasha Grievus Jan 25 '16 at 10:22

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.