Skip to content Skip to sidebar Skip to footer

Pass Left Click Message To Html Element Below Another One

I have 2 HTML elements that sit in the exact same position(same x,y values & same width & height). They also have the same z-index. Both listen to left click events but bec

Solution 1:

You can use the pointer-eventscss property:

.click-thru {
  pointer-events: none;
}

This will make it so that clicks on the element travel through to the element below it. However, the top element won't get the click event, so this might not work for you.

You can also try using a global click handler and document.getElementAtPoint to manually trigger the event on the both elements.

// Example (with jQuery)
$(document).click(function(e){
  var mouseX = e.pageX, mouseY = e.pageY;
  if(mouseIsOverElement(mouseX, mouseY, element1))
  {
    $(element1).click();
  }
  if(mouseIsOverElement(mouseX, mouseY, element2))
  {
    $(element2).click();
  }
});

// Possible implementation of mouseIsOverElementfunctionmouseIsOverElement(x, y, ele)
{
  var result = false;

  // Hide both
  $(element1).hide();
  $(element2).hide();

  // Show the target element
  $(ele).show();

  if(document.getElementAtPoint(x,y)===ele)
  {
    result = true;
  }

  $(element1).show();
  $(element2).show();

  return result;
}

Solution 2:

One option is to place the groups of elements that need to share a click into another element and handle the click there.

If you are designing a game and have many elements where this will be occurring, what you would have to do is actually assign a single click handler to the entire body of the web page and calculate which element is clicked on. It's actually quite quick to do this. For more information, watch this Google Tech Talk.

Solution 3:

On my phone so I can't post proper code, but would it not be a case of binding a function that triggers the second element when you click the first? Something along the lines of:

$('#a').bind('click', function(){
  $('#b').click();
});

In jQuery?

Post a Comment for "Pass Left Click Message To Html Element Below Another One"