I want clicking on an "expando" to toggle between its states: expanded and collapsed.
I'm still pretty new to DOM/JS, so my style here is probably awful; If you have any style guidelines let me know, but for right now I want to get the code working. I've tried a few different ways, like setting the expand or collapse behavior in dom's onclick (and changing it in the expand and collapse functions), but if I do that, then for some reason clicking doesn't trigger a collapse, but it will trigger an expand.
The problem with the code below is that I can expand an expando, but when I click on it, it also triggers the collapse, so it expands and then immediately collapses back.
var expandos = document.getElementsByTagName("expando");
var uid = 0;
for(var i=0; i<expandos.length; ++i) {
var dom = expandos[i];
dom.id = "expando_"+uid++;
var iframe = document.createElement("iframe");
iframe.src = dom.innerHTML;
iframe.name = dom.id +".big";
iframe.id = iframe.name;
iframe.scrolling = "no";
iframe.style.display = "inline";
iframe.onclick = collapse(dom);
var p = document.createElement("p");
var text = document.createTextNode(dom.innerHTML);
p.id = dom.id+".small";
p.style.display = "inline";
p.appendChild(text);
p.onclick = expand(dom);
dom.innerHTML = "";
/* We have to clear the innerHTML to prevent the original text from
showing up in addition to the text added by p.
*/
dom.appendChild(iframe);
dom.appendChild(p);
/* We have to append iframe and p **after** we clear innerHTML
because otherwise clearing innerHTML will clear the appended
children.
*/
function expand(dom) {
return function() {
alert("Expanding "+dom.id);
var iframe = document.getElementById(dom.id+".big");
var p = document.getElementById(dom.id+".small");
p.style.display = "none";
iframe.style.display = "initial";
dom.onclick = collapse(dom);
}
}
function collapse(dom) {
return function() {
alert("Collapsing "+dom.id);
var iframe = document.getElementById(dom.id+".big");
var p = document.getElementById(dom.id+".small");
p.style.display = "initial";
iframe.style.display = "none";
dom.onclick = expand(dom);
}
}
collapse(dom)();
}
The sample HTML I'm testing on:
<body>
<expando>The quick brown</expando> fox jumps over <expando>the lazy dog</expando>.
<script src="loadExpandos.js"></script>
</body>
In the same directory, I have files named "The quick brown" and "the lazy dog", and they expand properly.
A quick fix for to get the basic functionality you want is to combine your expand and collapse into a single function and have an if/else block that checks the state. Not 100% on what caused your original issue, but I'd guess it has something to do with your onClick events not being cleared.
function clickHandler(dom) {
return function() {
var iframe = document.getElementById(dom.id+".big");
var p = document.getElementById(dom.id+".small");
if(p.style.display === "initial"){
p.style.display = "none";
iframe.style.display = "initial";
} else {
p.style.display = "initial";
iframe.style.display = "none";
}
Related
The following code takes all the links onto the page that contains "https" and not "google.com" and turns them into iFrames. While that works, the close button that each is iFrame is supposed to be paired with does not work. When you click close, it only closes the last iFrame element on the page. I prefer to be able to do this in vanilla JavaScript, as opposed to jQuery.
total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (link.href.indexOf("https") != -1 &&
link.href.indexOf("google.com") == -1) {
var hey = (links[i].href);
console.log(link.href);
total.push(links[i].href);
var iframe = document.createElement('iframe');
iframe.src = hey;
document.body.appendChild(iframe);
var close = document.createElement('button');
document.body.appendChild(close);
close.innerHTML = "close";
close.addEventListener('click',function(){
console.log("click");
document.body.removeChild(iframe);
document.body.removeChild(close);
})
}
}
It's a Variable Hoisting issue
where the var is hoisted to the closest scope, in your case it's window (since you don't have any other parent function wrapper), and reassigned/overridden again and again inside the loop - always leading to the last iterated element.
Quickfix:
var iframe and var close should be defined as const to remain inside the scope of that for loop body:
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
const iframe = document.createElement('iframe'); // Quickfix
iframe.src = links[i].href;
iframe.id = Math.random();
document.body.appendChild(iframe);
const close = document.createElement('button'); // Quickfix
document.body.appendChild(close);
close.innerHTML = "close " + link.href;
close.addEventListener('click', function() {
document.body.removeChild(iframe);
document.body.removeChild(close);
})
}
}
The proper way
not only it's a bad habit to use var nowadays, it's also a bad practice to assign Event handlers inside a for loop. So here's a remake which removed completely the var keyword, uses some nifty reusable DOM utility functions, and at last — the NodeList.prototype.forEach() method:
// DOM utility functions:
const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Task:
// Convert all http/s anchors to iframes with a
// button "Delete", wrapped inside a .figure DIV Element
ELS("a").forEach(EL_anchor => {
const href = EL_anchor.href;
if (/^https?:\/\/(?:(?:www\.)?google.com)/.test(href)) return;
const EL_figure = ELNew("div", {className: "figure"});
const EL_iframe = ELNew("iframe", {src: EL_anchor.href});
const EL_delete = ELNew("button", {type: "button", textContent: "Delete", onclick() {EL_figure.remove();}});
EL_figure.append(EL_iframe, EL_delete);
EL("body").append(EL_figure);
});
See the above's RegExp Example and desctription on Regex101.com
JS is not my primary language, but try this:
total = []
var links = document.querySelectorAll("a");
for (var i = 0; i < links.length; i++) {
var link = links[i];
if (link.href.indexOf("https") != -1 && link.href.indexOf("google.com") == -1) {
var hey = (links[i].href);
console.log(link.href);
total.push(links[i].href);
var iframe = document.createElement('iframe');
iframe.src = hey;
document.body.appendChild(iframe);
var close = document.createElement('button');
document.body.appendChild(close);
close.innerHTML = "close";
close.addEventListener('click',function(){
console.log("click");
document.body.removeChild(iframe);
document.body.removeChild(close);
document.body.removeChild(document.getElementById("iframe"));
});
}
}
for (var i = 0; i < links.length; i++)
Change var to let.
OR
Use forEach instead of for loop.
The reason of this is scoping. var is function-scoped. Because above loop runs inside one function, var remains common for all loop iteration. On the other side, let or const are block-scoped. Because for loop creates individual blocks, each of the blocks created by the loop will work with an individual variable. forEach also creates individual scope. All variables will have values independent from each scope
If I understand correctly you want to create an <iframe> based on the href of pre-existing <a>s. You also want a <button> for each <iframe> that closes it.
In the example below are two functions:
linksToIframes(urlFrag)
Creates a box to put <iframe>s and <button>s into. Throwing them on <body> is messy:
document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
const box = document.querySelector('fieldset');
Given a fragment of a url, it will collect all <a> into a HTMLCollection:
const links = document.links
Convert HTMLCollection into an array and iterate through it finding any matches of href and urlFrag:
[...links].forEach(link => {
if (link.href.includes(urlFrag)) {...
Any match create the <frame> and <button> in the <fieldset> (the box):
let iF = document.createElement('iframe');
iF.src = link.href;
box.appendChild(iF);
...
closeIframe(event)
An event handler that enables any <button> to remove the <frame> before it and itself:
const clicked = e.target; // This is the tag user actually clicked
if (clicked.matches('button')) { /* <button> is the only
tag that's accepted (that's
Event Delegation) */
clicked.previousElementSibling.remove();
clicked.remove();
...
Because of event bubbling we can bind the event handler on the parent element of all of the <button>s and then delegate how they react to a click. That's far better than an event handler on each <button>.
If you stick to your OP code, .previousElementSibling.remove(); applied to each <button> and .remove() to itself should fix it.
const linksToIframes = urlFrag => {
document.body.insertAdjacentHTML('afterBegin', `<fieldset></fieldset>`);
const box = document.querySelector('fieldset');
const links = document.links;
[...links].forEach(link => {
if (link.href.includes(urlFrag)) {
let iF = document.createElement('iframe');
iF.src = link.href;
box.appendChild(iF);
let btn = document.createElement('button');
btn.textContent = 'Close';
box.appendChild(btn);
}
});
};
const closeIframe = e => {
const clicked = e.target;
if (clicked.matches('button')) {
clicked.previousElementSibling.remove();
clicked.remove();
}
}
linksToIframes('https://example.com');
document.querySelector('fieldset').onclick = closeIframe;
a,
iframe,
button {
display: block
}
iframe {
width: 95%;
max-height: 50px;
}
<a href='https://example.com'>EXAMPLE</a>
<a href='https://stackoverflow'>SO</a>
<a href='https://example.com'>EXAMPLE</a>
<a href='https://example.com'>EXAMPLE</a>
Popup won't close when i click close button, i tried debugging with console.log and it looks like closeButton.onclick function doesn't run at all for some reason.
When running close() function manually from the console everything works fine.
class Popup {
constructor(content){
this.div = document.createElement("div");
this.div.className = "block";
//tried positioning popup into the center of the screen, doesn't work yet
this.div.style.position = "fixed";
this.div.style.margin = "auto auto";
//caption
this.caption = document.createElement("div");
this.caption.style.textAlign = "right";
//closeButton
this.closeButton = document.createElement("button");
this.closeButton.textContent = "X";
this.closeButton.onclick = this.close;
document.body.appendChild(this.div);
this.div.appendChild(this.caption);
this.caption.appendChild(this.closeButton);
this.div.innerHTML += content;
}
close(){
this.div.parentNode.removeChild(this.div);
delete this;
}
}
new Popup("close me");
That's how it looks like:
var popup = new Popup("hm hello");
SOLUTION:
The issue was happening because:
I was appending content of the popup right into main div using +=. That made DOM refresh and onclick trigger reset.
this.closeButton.onclick = this.close; here onclick trigger will execute close function and also will overwrite this keyword, so it contains a button that called trigger, not the Popup object. I decided to put Popup into a variable that is visible to onclick function. Now everything works fine.
class Popup {
constructor(content){
this.div = document.createElement("div");
this.div.className = "block";
this.div.style.position = "fixed";
this.div.style.margin = "auto auto";
//делоем капшон
this.caption = document.createElement("div");
this.caption.style.textAlign = "right";
//кнопка закрытия
this.closeButton = document.createElement("button");
this.closeButton.textContent = "X";
let popup = this;
this.closeButton.onclick = function(){popup.close()};
this.content = document.createElement("div");
this.content.innerHTML = content;
this.caption.appendChild(this.closeButton);
this.div.appendChild(this.caption);
this.div.appendChild(this.content);
document.body.appendChild(this.div);
}
close(){
this.div.parentNode.removeChild(this.div);
delete this;
}
}
new Popup("hello guys");
The issue is that right here:
this.div.innerHTML += content;
When you assign a value to .innerHTML, the entire previous value is overwritten with the new value. Even if the new value contains the same HTML string as the previous value, any DOM event bindings on elements in the original HTML will have been lost. The solution is to not use .innerHTML and instead use .appendChild. To accomplish this in your case (so that you don't lose the existing content), you can create a "dummy" element that you could use .innerHTML on, but because of performance issues with .innerHTML, it's better to set non-HTML content up with the .textContent property of a DOM object.
You were also going to have troubles inside close() locating the correct parentNode and node to remove, so I've updated that.
class Popup {
constructor(content){
this.div = document.createElement("div");
this.div.className = "block";
this.div.style.position = "fixed";
this.div.style.margin = "auto auto";
//caption
this.caption = document.createElement("div");
this.caption.style.textAlign = "right";
//closeButton
this.closeButton = document.createElement("button");
this.closeButton.textContent = "X";
this.closeButton.addEventListener("click", this.close);
this.caption.appendChild(this.closeButton);
this.div.appendChild(this.caption);
// Create a "dummy" wrapper that we can place content into
var dummy = document.createElement("div");
dummy.textContent = content;
// Then append the wrapper to the existing element (which won't kill
// any event bindings on DOM elements already present).
this.div.appendChild(dummy);
document.body.appendChild(this.div);
}
close() {
var currentPopup = document.querySelector(".block");
currentPopup.parentNode.removeChild(currentPopup);
delete this;
}
}
var popup = new Popup("hm hello");
I've finally found a final solution.
As Scott Marcus mentioned in his answer, i will have troubles inside close function, so i decided to put Popup object into a variable that is visible to close function. Everything works fine without applying classes. Though it may look like a bad code.
class Popup {
constructor(content){
this.div = document.createElement("div");
this.div.className = "block";
this.div.style.position = "fixed";
this.div.style.margin = "auto auto";
//делоем капшон
this.caption = document.createElement("div");
this.caption.style.textAlign = "right";
//кнопка закрытия
this.closeButton = document.createElement("button");
this.closeButton.textContent = "X";
let popup = this;
this.closeButton.onclick = function(){popup.close()};
this.content = document.createElement("div");
this.content.innerHTML = content;
this.caption.appendChild(this.closeButton);
this.div.appendChild(this.caption);
this.div.appendChild(this.content);
document.body.appendChild(this.div);
}
close(){
this.div.parentNode.removeChild(this.div);
delete this;
}
}
new Popup("hello guys")
P.S.
What's the point of this restriction?
Yesterday I asked a question about improving efficiency in my code. Today I have another question in the same spirit of trying to write less lines of code to accomplish repetitive tasks.
I have the following code:
function myIntroductionText() {
introPos.style.display = 'block';
posOne.style.display = 'none';
posTwo.style.display = 'none';
posThree.style.display = 'none';
posFour.style.display = 'none';
posFive.style.display = 'none';
posSix.style.display = 'none';
posSeven.style.display = 'none';
posEight.style.display = 'none';
posNine.style.display = 'none';
posTen.style.display = 'none';
posEleven.style.display = 'none';
backButton.style.visibility = 'hidden';
}
function myPositionOne() {
introPos.style.display = 'none';
posOne.style.display = 'block';
posTwo.style.display = 'none';
posThree.style.display = 'none';
posFour.style.display = 'none';
posFive.style.display = 'none';
posSix.style.display = 'none';
posSeven.style.display = 'none';
posEight.style.display = 'none';
posNine.style.display = 'none';
posTen.style.display = 'none';
posEleven.style.display = 'none';
backButton.style.visibility = 'visible';
}
function myPositionTwo() {
introPos.style.display = 'none';
posOne.style.display = 'none';
posTwo.style.display = 'block';
posThree.style.display = 'none';
posFour.style.display = 'none';
posFive.style.display = 'none';
posSix.style.display = 'none';
posSeven.style.display = 'none';
posEight.style.display = 'none';
posNine.style.display = 'none';
posTen.style.display = 'none';
posEleven.style.display = 'none';
}
The HTML looks something like this:
<p class="textContent" id="introductionText">Introduction Text Goes Here</p>
<p class="textContent" id="position1">content1</p>
<p class="textContent" id="position2">content2</p>
<p class="textContent" id="position3">content3</p>
Each position (i.e. introPos, posOne, posTwo) also has a corresponding function that looks essentially the same as the function above, except it changes the display based on which position it is in.
I'm thinking that I could use a loop and/or an if/else statement to make this task more efficient. I tried by using getElementsByClassName('textContent'), which (I think) produced an array containing all of the elements with that class. According to the console.log is contains [p#introductionText.textContent, p#position1.textContent, so on and so on...]. So, I wrote the following code to try to loop through it:
var blanks = document.getElementsByClassName("textContent") // this creates the array that I mentioned
for (item in blanks) {
if (blanks[0] === introductionText.textContent) {
blanks[0].style.display = 'block';
} else {
blanks[item].style.display = 'block';
}
}
I tried using p#introductionText.textContent but that returned an error. I'm very new to JavaScript so I fully recognize that I could be doing something very silly here, but any help would be appreciated.
EDIT:
The error message says Uncaught SyntaxError: Unexpected tocken ILLEGAL
I should also add that my goal is to have only one position be visible at each time. I have a "Back" and "Next" button that allows users to go from posOne to posTwo, to posThree, and so on. So, in addition to making posTwo visible, I also need to make posOne and/or posThree not visible.
Thanks!
The first thing is moving all those Javascript style expressions to CSS:
#introPos,
#posOne,
#posTwo,
#posThree,
#posFour,
#posFive,
#posSix,
#posSeven,
#posEight,
#posNine,
#posTen,
#posEleven {
display: none;
}
Or even shorter
#introductionText>.textContent {
display: none;
}
This would enable you to shorten each function considerably:
function myPositionOne() {
posOne.style.display = 'block';
backButton.style.visibility = 'visible';
}
Instead of setting each style via JS again and again, you'd simply set those that change.
The next step would be to rewrite all those functions into one that accepts a parameter which element you are targeting:
function myPosition(pos) {
var parent = document.getElementById("text-container");
var children = parent.getElementsByClassName("textContent");
var element;
// first hide all <p class="textContent"> children
for (var i = 0; i < children.length; i++) {
children[i].style.display = 'none';
if (i == pos) {
element = children[i];
}
}
// then show the right one
if (element) {
element.style.display = 'block';
}
// show or hide the back button depending on which child we are dealing with
if (pos > 0) {
document.getElementById("backButton").style.visibility = 'visible';
} else {
document.getElementById("backButton").style.visibility = 'hidden';
}
if (pos >= children.length-1) {
document.getElementById("nextButton").style.visibility = 'hidden';
} else {
document.getElementById("nextButton").style.visibility = 'visible';
}
}
This sets only the child number #pos visible and adjusts the visibility of the back button (assuming the back button has the ID "backButton").
Maybe this:
All paragraphs also have the class "textContent". Make this display none and display the correct paragraph via given paragraph-id:
function myFunction(classDisplay) {
var elems = document.getElementsByClassName('textContent');
for (var i=0;i<elems.length;i+=1){
elems[i].style.display = 'none';
}
document.getElementById(classDisplay).style.display = "block";
}
The following will hide all but position 2:
myFunction("position2");
I don't know about the back-button, this is always be visible?
EDIT: I've tested this and corrected the code.
If you use JQuery, you can also use the following instead of the for loop:
$('.textContent').css('display','none');
In newer versions of JavaScript you can use:
Array.from(document.getElementsByClassName('myclass')).forEach((item) => {
item.style.backgroundColor = "blue";
})
I am in the process of making a bookmarklet that pops up a div with various things in it... when you click on the link to open the bookmarklet twice, two bookmarklets pop up. how do I prevent this from happening?
index.html:
<html>
<head>
<title>Bookmarklet Home Page</title>
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body>
click here
</body>
</html>
code.js:
function toggle_bookmarklet() {
bookmarklet = document.getElementById("bookmarklet");
if (bookmarklet.style.display == "none") {
bookmarklet.style.display = "";
}
else {
bookmarklet.style.display = "none";
}
}
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
content = "";
content += "<a href='javascript:void(0);'><div id='xbutton' onClick='javascript:toggle_bookmarklet();'>x</div></a>";
div.innerHTML = content;
document.body.appendChild(div);
Just check for the existence of div before creating it.
var div = document.getElementById("bookmarklet");
if (!div)
{
div = document.createElement("div");
div.id = "bookmarklet";
div.style.margin = "auto";
div.style.position = "fixed";
}
Also, since you already have a global reference to div, you don't need to search for it by id in toggle_bookmarklet. You can just reference div. I'd try to choose a more unique name though, so as to avoid running in to naming collisions.
Edit: For that matter, if you are going to use a global variable, you can simplify further. Don't even bother giving it an id, just use the global reference:
function toggle_bookmarklet() {
bookmarkletEl.style.display = bookmarkletEl.style.display == "none" ? "" : "none";
}
if (!window.bookmarkletEl) {
var bookmarkletEl = ddocument.createElement("div");
bookmarkletEl.style.margin = "auto";
bookmarkletEl.style.position = "fixed";
}
Yes, I've searched high and low on Stack Overflow and seen some great solutions to this problem that's been solved time and time again with things like SimpleModal, jQuery.confirm and the like.
Problem is, I am developing for this low level device that doesn't allow for a JS framework to be utilized AND I am having to shoehorn this modal confirm into existing JS.
There is an existing script that I am at liberty to edit (but not rewrite) that does a few things like validate, concatenate a few inputs into a single variable, and more.
The script was written to:
Take some session variables and assign new variable names to them and format accordingly
Present a confirm to the user to see whether they want to use those variables to pre-populate the form on the page
Get some functions ready to validate inputs.
other stuff, like offer an abandonment scenario, among other things
Now, all was good when the "confirm" was in place as the script would pause until an OK or Cancel was provided. I am now presenting a modal on the page that I want to mock this behavior and the only way I can think of doing it is to remove that reliance on the line that goes through the confirm thing and NOT run the script until the user interacts with the modal.
Does anyone have an idea how to take what's in place and "wrap" it in a "listening" if/else scenario for each of the YES or NO possibilities?
Sorry if this is jumbled... my brain is all blended up at the moment, too.
As far as I know there is - so far - no way to halt scripts like the Browser specific alert() or confirm() Dialog does.
Frameworks like dojo for example try to mock this behaviour by putting a transparent DIV over the whole window to prevent clicks or other input while the Dialog is showing.
This is quite tricky as I have experienced, since Keyboard-Input may be able to activate Input Fields or Buttons behind this curtain. Keyboard Shortcuts or Field-Tabbing for example.
One sollution is to disable active Elements manually, which works quite well with me in most cases.
One or more function is passed to this "mock" Dialog to execute when an option was chosen.
Escpecially with ajax background activity the responsibilty to stop conflicting function calls while the Dialog is open lies with the developer.
Here is an example I came up with:
<html>
<head>
<title>Modal Dialog example</title>
<script type="text/javascript">
<!--
var ModalDialog = function(text,choices){
this._text = text;
this._choices = choices;
this._panel = null;
this._modalDialog = null;
this._disableElements = function(tag){
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++){
elements[i].disabled = true;
}
};
this._enableElements = function(tag){
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++){
elements[i].disabled = false;
}
};
this._disableBackground = function(){
if(this._panel){
this._panel.style.display = 'block';
}
else{
// lower the curtain
this._panel = document.createElement('div');
this._panel.style.position = 'fixed';
this._panel.style.top = 0;
this._panel.style.left = 0;
this._panel.style.backgroundColor = 'gray';
this._panel.style.opacity = '0.2';
this._panel.style.zIndex = 99; // make sure the curtain is in front existing Elements
this._panel.style.width = '100%';
this._panel.style.height = '100%';
document.body.appendChild(this._panel);
// Disable active Elements behind the curtain
this._disableElements('INPUT');
this._disableElements('BUTTON');
this._disableElements('SELECT');
this._disableElements('TEXTAREA');
}
};
this.close = function(){
// Hide Curtain
this._panel.style.display = 'none';
// Hide Dialog for later reuse - could also be removed completely
this._modalDialog.style.display = 'none';
// reactivate disabled Elements
this._enableElements('INPUT');
this._enableElements('BUTTON');
this._enableElements('SELECT');
this._enableElements('TEXTAREA');
};
this.open = function(){
var _this = this;
this._disableBackground();
if(this._modalDialog){
this._modalDialog.style.display = 'block';
}
else{
// create the Dialog
this._modalDialog = document.createElement('div');
this._modalDialog.style.position = 'absolute';
this._modalDialog.style.backgroundColor = 'white';
this._modalDialog.style.border = '1px solid black';
this._modalDialog.style.padding = '10px';
this._modalDialog.style.top = '40%';
this._modalDialog.style.left = '30%';
this._modalDialog.style.zIndex = 100; // make sure the Dialog is in front of the curtain
var dialogText = document.createElement('div');
dialogText.appendChild(document.createTextNode(this._text));
// add Choice Buttons to the Dialog
var dialogChoices = document.createElement('div');
for(i = 0; i < this._choices.length; i++){
var choiceButton = document.createElement('button');
choiceButton.innerHTML = this._choices[i].label;
var choiceAction = _this._choices[i].action
var clickAction = function(){
_this.close();
if(choiceAction)choiceAction();
};
choiceButton.onclick = clickAction;
dialogChoices.appendChild(choiceButton);
}
this._modalDialog.appendChild(dialogText);
this._modalDialog.appendChild(dialogChoices);
document.body.appendChild(this._modalDialog);
}
};
};
var myConfirm = function(text,okAction){
var dialog = new ModalDialog(text,[
{
label:'ok',
action : function(){
console.log('ok')
okAction();
}
},
{
label:'cancel'
}
]);
dialog.open();
};
-->
</script>
</head>
<body>
<form name="identity" action="saveIdentity.do">
<label>Firstname</label><input name="name" type="text"><br>
<label>Lastname</label><input name="name" type="text"><br>
<input type="button"
value="submit"
onclick="if(myConfirm('Do you really want to Commit?',function(){ document.forms['identity'].submit();}));">
</form>
</body>
</html>
In this code there is still an error concerning the availability of the stored choice-function (undefined) at execution time. The function variable is no longer available in the closure. If anyone has a sollution for this you are welcome to add to it.
Hope that comes near to what you need to know.
Updated version: fixed choiceAction undefined, added IE compatibility. Internet Explorer is one main reason to use this, since confirm() is now blocked by default.
<!doctype html>
<html><head>
<title>Modal Dialog example</title>
<script type="text/javascript"><!-- //http://stackoverflow.com/questions/4739740/yet-another-confirm-replacement-quesiton
var ModalDialog = function(text,choices) {
this._text = text;
this._choices = choices;
this._panel = null;
this._modalDialog = null;
this._disableElements = function(tag) {
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++) {
elements[i].disabled = true;
}
};
this._enableElements = function(tag) {
var elements = document.getElementsByTagName(tag);
for(i=0; i < elements.length; i++) {
elements[i].disabled = false;
}
};
this._disableBackground = function() {
if(this._panel) {
this._panel.style.display = 'block';
}
else {
// lower the curtain
this._panel = document.createElement('div');
this._panel.style.position = 'fixed';
this._panel.style.top = 0;
this._panel.style.left = 0;
this._panel.style.backgroundColor = '#000';
this._panel.style.opacity = '0.3';
this._panel.style.filter = 'alpha(opacity=30)'; //ie7+
this._panel.style.zIndex = 99; // make sure the curtain is in front existing Elements
this._panel.style.width = '100%';
this._panel.style.height = '100%';
document.body.appendChild(this._panel);
// Disable active Elements behind the curtain
this._disableElements('INPUT');
this._disableElements('BUTTON');
this._disableElements('SELECT');
this._disableElements('TEXTAREA');
}
};
this.close = function() {
// Hide Curtain
this._panel.style.display = 'none';
// Hide Dialog for later reuse - could also be removed completely
this._modalDialog.style.display = 'none';
// reactivate disabled Elements
this._enableElements('INPUT');
this._enableElements('BUTTON');
this._enableElements('SELECT');
this._enableElements('TEXTAREA');
};
this.open = function() {
var _this = this;
this._disableBackground();
if(this._modalDialog) {
this._modalDialog.style.display = 'block';
}
else {
// create the Dialog
this._modalDialog = document.createElement('div');
this._modalDialog.style.position = 'absolute';
this._modalDialog.style.backgroundColor = 'white';
this._modalDialog.style.border = '1px solid black';
this._modalDialog.style.padding = '16px';
this._modalDialog.style.top = '35%';
this._modalDialog.style.left = '30%';
this._modalDialog.style.zIndex = 100; // make sure the Dialog is in front of the curtain
var dialogText = document.createElement('div');
dialogText.style.padding = '0 10px 10px 0';
dialogText.style.fontFamily = 'Arial,sans-serif';
dialogText.appendChild(document.createTextNode(this._text));
// add Choice Buttons to the Dialog
var dialogChoices = document.createElement('div');
for(i = 0; i < this._choices.length; i++) {
var choiceButton = document.createElement('button');
choiceButton.style.marginRight = '8px';
choiceButton.name = i;
choiceButton.innerHTML = this._choices[i].label;
var clickAction = function() {
_this.close();
if(_this._choices[this.name].action) _this._choices[this.name].action();
};
choiceButton.onclick = clickAction;
dialogChoices.appendChild(choiceButton);
}
this._modalDialog.appendChild(dialogText);
this._modalDialog.appendChild(dialogChoices);
document.body.appendChild(this._modalDialog);
}
};
};
var myConfirm = function(text,okAction){
var dialog = new ModalDialog(text,[
{
label : 'OK',
action : function() {
console.log('ok');
okAction();
}
},
{
label : 'Cancel'
}
]);
dialog.open();
};
-->
</script>
</head>
<body>
<form name="identity" action="saveIdentity.do">
<label>Firstname</label><input name="name" type="text"><br>
<label>Lastname</label><input name="name" type="text"><br>
<input type="button" value="submit"
onclick="if(myConfirm('Do you really want to Commit?',function(){ alert('submitted') }));">
<!-- document.forms['identity'].submit(); -->
</form>
</body>
</html>