简体   繁体   中英

prevent overlay from closing on click

I have a page where I send a message. When the message is sent an overlay appears on the page. The overlay will prevent the user from clicking anywhere on the page but will force the user to click a button when he wants to stop the message to be displayed on the client device.

The overlay is made of a small box (300 x 200 px) placed in the center of the screen. Inside it there are a message and a button:

<div id="box">
    <h1>ALLARME <br>IN CORSO</h1>
    <form name="fermare"><button  name="al_fermare" class="btn btn-danger">DISATTIVA</button></form>
</div>

If the user clicks outside the box div nothing happens (desired behaviour). If the user clicks the button the overlay is closed and some javascript is triggered (desired behaviour).

If the user clicks inside the box but not on the button the overlay is closed but the js is obviously not triggered. (not desired behaviour).

I have two ways of solving this:

  1. trigger the js also on click event on the box div;
  2. prevent anything from happening on click in the box outside the button;

How can I get point 2? This would be the best solution.

The triggered js is the following:

document.forms['fermare'].elements['al_fermare'].onclick = function(event){
  websocket.send("all_fine:"+messaggio_in);
  return false;
}

EDIT: i tried with preventDefault and return false and these are not working as solution.

document.getElementById('box').onclick = function(e){
  e.preventDefault();
}

I also tried:

document.getElementById('box').onclick = function(e){
  return false;
}

or the proposed answers in this direction.

EDIT 2: this works but is the behaviour on point 1. Seems I cannot trigger the behaviour described in point 2:

document.getElementById('box').onclick = function(e){
  websocket.send("all_fine:"+messaggio_in);
  return false;
}

Try this:

<div id="box" onclick="return false;">
    <h1>ALLARME <br>IN CORSO</h1>
    <form name="fermare"><button  name="al_fermare" class="btn btn-danger">DISATTIVA</button></form>
</div>

 Javascript: ----------- var myFunc = function(e){ e.stopImmediatePropagation(); }
 HTML: ----- <div id="box" onclick="myFunc(event)"> <h1>ALLARME <br>IN CORSO</h1> <form name="fermare"><button name="al_fermare" class="btn btn-danger">DISATTIVA</button></form> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM