Thursday, June 13, 2013

A simple way to detect mouse-click on a page element and opening a popups

document.onclick = document.getElementsByTagName('td').onclick = function(e)
{
  if (e.target.tagName.toLowerCase() == 'td' && e.target.parentNode.id != '')
  {
    document.getElementById('popupbg').style.visibility = "visible";
    document.getElementById('popup').style.display = "inline";
    document.getElementById('popupresults').style.display = "inline";
    /* On this line you can put some logic for getting values and sending them to some PHP script
    For example 'e.target.parentNode.id;' can be used as SQLite table row variable for
    SELECT/INSERT/DELETE queries
    Another example is using 'document.getElementById('popupresults').innerHTML' for visualising
    the answer of the PHP script */
  }
};

This small snippet works on Firefox and Chrome (not tested on IE and Opera) and does the following:
  • detects the tag of a clicked element
  • checks if its parent has an id (usefull for AJAXing values from some HTML table to PHP) and sends the data using your home-brew AJAX function
  • reveals divs that hold popup data (div 'popup', div 'popupbg' for disabling clicking on background elements, div 'popupresults' for visualising the PHP answer; all of them can use 'display: none' or 'visibility: hidden' CSS attributes as default visual state)