Scroll to top

12/05/2022


2022/05/12#p1

0 comments: click to leave a comment

Couldn't sleep, wrote code.

Rather than just clicking the menu toggle I also wanted to be able to click the page away from the menu and have it close. I knew I'd be able to use click events via jQuery but just needed to figure out how.

The bulk of the main content is held within a div with ID 'page' so this is the obvious element on which to check for click events. The menu toggle is actually the label for a hidden checkbox (menu_tray_checkbox) and the menu slides using the translateX css transform.

You can't get the value of translateX directly so have to extract it from the transform – css('transform') returns a matrix of values as below:

matrix(scaleX, skewY, skewX, scaleY, translateX, translateY)

so it's a simple matter of getting the right value from the list, seeing if the checkbox is currently checked and unchecking it to hide the menu. Here's the code:

$('#page').click(function(event) {
    var posx = $('#menu_tray').css('transform').split(',')[4];
    if ($('#menu_tray_checkbox').prop('checked', true) && posx != 0) {
        $('#menu_tray_checkbox').prop('checked', false);
    }
});

This should also be possible with normal JavaScript using addEventListener() so I'll probably look at reworking it so that the jQuery library doesn't need to be loaded on each page where not otherwise needed. I always overcomplicate things.

No comments yet
Leave a reply



You can also:

Click here to reply using email Reply by email Send a webmention Send a Webmention



2022/05/12#p2

0 comments: click to leave a comment

Examples of a JavaScript version can be found across the web so it's a case of modifying them slightly:

document.getElementById("page").addEventListener("click", hide_menu);

function hide_menu() {
  var style = window.getComputedStyle(menu_tray);
  var matrix = style['transform'] || style.webkitTransform || style.mozTransform;
  var posx = matrix.split(',')[4];
  if (document.getElementById('menu_tray_checkbox').checked && posx != 0) {
document.getElementById('menu_tray_checkbox').checked = false;
  }
}

It's not as clean but avoids adding jQuery to the payload.

No comments yet
Leave a reply



You can also:

Click here to reply using email Reply by email Send a webmention Send a Webmention



Close