2

After reading this question's answer

I was wondering how to structure a preventDefault / stopPropagation that depends on a user click event, for example:

<html>
   <a data-handler="add_to_cart" data-item_id="5">Click</a>
</html>

Clicking the element currently calls the backend (by ajax) to add item 5 to the user cart. But what if I want to inject a dialog first (javascript only)

var template = '' +
    '<div class="dialog">' +
        '<p>Really add this item?</p>' +
        '<button>Yes</button>' +
        '<button>No</button>' +
    '</div>'

$(a).click(function(){
    # open the dialog template
    # if the correct button is clicked continue the default event
});

I do not want to use confirm or prompt, I am basically looking for a way to implement their functionality with my own html dialog.

Community
  • 1
  • 1
user2298943
  • 632
  • 5
  • 20
  • 1
    You should use `confirm`, it's cross-browser, accessible, and works everywhere, including mobile devices. – user229044 Apr 29 '13 at 13:36

2 Answers2

0

You have several options to accomplish this. The two I would suggest is either overriding the prompt method (see here and here about overriding and changing looks), or making your own dialog and monitoring the buttons on it.

Overriding:

function prompt() { 
    //Insert your HTML, show the dialog
} 

Monitor another click:

$('#someOtherButton').click(function(){
    //Do what you want
});

I would suggest simply overriding prompt().

Community
  • 1
  • 1
nwalke
  • 3,170
  • 6
  • 35
  • 60
0

You can prevent propagation and re-call the click() method from the dialog, and ask for propagation.

var template = '' +
    '<div class="dialog">' +
        '<p>Really add this item?</p>' +
        '<button class=correctbutton>Yes</button>' +
        '<button>No</button>' +
    '</div>'

$(a).click(function(){
    if(window.correctButtonClicked){
     return true;//continue propagation
    }
    window.clickedA=a // store current clicked object
    openDialog() 
    return false; //stop propagation
});

function openDialog(){
 //Make a dialog from the template
 $('.correctbutton').click(function(){
      window.correctButtonClicked=true;
      $(window.clickedA).click(); 
 });

}
Manishearth
  • 14,882
  • 8
  • 59
  • 76