Articles


How to programmatically create a simple popup block in drupal?

How to programmatically create a simple popup block in drupal?



Posted bysivaprasad,27th Mar 2017

There are many modules available for creating a popup block in Drupal7. But it is much simpler to programmatically create a popup in Drupal using the jquery modal.

First, we have to load the external js file for the jquery default modal structure. 
Paste this code to your template.php


function MYTHEME_preprocess_page(&$variables) {
  drupal_add_js('https://code.jquery.com/jquery-1.12.4.js', 'external');
  drupal_add_js('https://code.jquery.com/ui/1.12.1/jquery-ui.js', 'external');
}

Then add a block inside the site with class name as popup and add your content

Then add a custom js file and paste this code

(function ($) {
  $(function () {
    $(".popup").dialog({
      modal: true,
      autoOpen: false,
      // custom close button
      buttons: {
        "X": function () {
          $(this).dialog("close")
        }
      },
      // for aligning block in center
      my: "center",
      at: "center",
      of: window,
      // effects to show the popup
      show: {
        effect: 'fadeIn',
        duration: 500
      },
      hide: {
        effect: 'fadeOut',
        duration: 500
      }      
    });
    // popup on a specific page load
    if (window.location.pathname != ('/test')) {
      $(window).load(function() {
        $('.popup').dialog('open');
      });
    }
    // popup on a button click
    $("button").click(function () {
      $('.popup').dialog('open');
    });
  });
})(jQuery);

Style your popup block as your desired design.

Categories