Making a Javascript Yes/No Confirmation Box? - javascript

well Javascript confirmation gives the Ok/Cancel Button but I want to create a Confirmation with Yes and No in Javascript can anyone help ??

The buttons in a confirmation box cannot be changed by Javascript.
I would suggest rolling your own in the form of an inline popup. Just create a div with position:absolute; in the centre of the page and then show/hide it.
EDIT:
The code below will outline what you need to do in vanilla Javascript. You will probably want to spend more time styling it, but the key points are:
position:absolute; So that the popup will appear in the centre of the page.
display:none; So that the popup will be hidden when the page loads.
The link has a href so that it will still be functional even without Javascript.
The onClick attribute of the first link has return false; This stops the link from redirecting.
You can change the two onClicks inside the popup to do whatever else you want them to.
<style type="text/css">
div#popup
{
position:absolute;
display:none;
top:200px;
left:50%;
width:500px;
margin-left:-250px;
border:1px solid blue;
padding:20px;
background-color:white;
}
</style>
<a
href="http://example.com/"
onclick="document.getElementById('popup').style.display = 'block'; return false;"
>Go to example.com</a>
<div id="popup">
<p>Are you sure you want to go to example.com?</p>
<p>
<a onclick="document.location='http://example.com/'; return false;">
Yes
</a>
<a onclick="document.getElementById('popup').style.display = 'none'; return false;">
No
</a>
</p>
</div>
To get a more professional result I would recommend learning more about JavaScript and jQuery and investigating some of the options suggested by the other posters.

The basics are:
Create a transparent (or semi-transparent) iframe to cover the browser viewport, which does a couple of things for you:
Eats clicks outside your confirmation box
Prevents OS-drawn controls (like select boxes) from appearing on top of your confirmation box (which they'll do otherwise, on IE at least and possibly others)
And lets you (optionally) shade the rest of the page to highlight your confirmation box. Give the iframe a z-index (100, say, unless you have other elements on the page with a higher z-index than that).
Create a div that contains your yes/no question and buttons, append it to your main page's DOM, position it where you want it, and give the div a z-index greater than that of the iframe. Believe it or not, this means that the page is behind the iframe, but the div is in front of it. Exactly what you want.
Handle clicks on the buttons to tear the whole thing down (and to get your answer).
Remember that this will not be inline with your JavaScript logic. You use callbacks from the buttons instead.
It really is that easy (or that complicated). :-)
Having said that, this wheel has been invented. Look for "lightbox" or similar components. jQuery UI has one called Dialog, for instance, but just adding that to a page where you're not using jQuery UI for anything else may be a bit heavy.

You cannot impact the use of the usual window.alert, window.confirm and window.prompt() native popup windows.
However, you could use other existing libraries for this, for instance ExtJS's MessageBox.
MessageBox is part of ExtCore, so you wouldn't even need the whole library but simply the core functions.
Below is an easy example, using the Google AJAX Libraries API loader.
within the <head> section of my.html:
<script type="text/javascript" src="http://www.google.com/jsapi?key=MY_API_KEY_GOES_HERE"></script>
<script type="text/javascript" src="my.js"></script>
in my.js:
google.load("dojo", "1.5", {
uncompressed: true
});
function OnLoad() {
function processResult() {
/* do something here */
}
Ext.Msg.show({
title:'Save Changes?',
msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
buttons: Ext.Msg.YESNOCANCEL,
fn: processResult,
icon: Ext.MessageBox.QUESTION
});
}
google.setOnLoadCallback(OnLoad);
For more information, you can refer to my answer to another question on how to use the Google CDN.

Related

Remove button hover effect after tap on mobile?

I have a basic JS flashcard game I made. There are 12 "answer buttons" for a user to choose from.
On mobile, the answer buttons retain the hover effect/focus(?) after being tapped (this does not happen on desktop, any browser). This is very confusing from a user standpoint as it can appear as though the app/flashcard is stuck or not updating.
I'm using Bootstrap 4.1.
Here is my button code, but there's nothing unusual about it:
<button type="button" id="E" class="btn btn-lg btn-info ansBtn" value="E">Answer</button>
I've looked at similar questions (but they were regarding bootstrap 3), which suggested using either an anchor tag instead of the button tag, but that didn't work (with and without the href attr).
I've also tried another suggestion to include this bit of jQuery, but it doesn't seem to work with 4.1 either. I've used button ID, and other classnames, but it has not worked.
$(".btn").mouseup(function(){
$(this).blur();
});
Suggestions? Thanks!
Update
So here is the latest. I've added the below CSS. This give mobile users the experience I want (a "flash" of background-color/border-color change only on click/tap). HOWEVER, now when using my macbook pro and TAPPING with my trackpad, the effect does not occur! It works when I click with the trackpad, but not tap with the track pad. :(
.btn.btn-info {
background-color: #17a2b8
}
.btn-info:not(:disabled):not(.disabled).active,
.btn-info:not(:disabled):not(.disabled):active,
.show > .btn-info.dropdown-toggle {
background-color: #117a8b;
border-color: #10707f;
}
You can always add a .setTimeout() function on the objects .onHover() or .onClick() event. This will allow your flashcard to be flipped/blurred after a certain amount of time. Alternatively, you can simply change the functionality of your application for mobile browsers and make it so you have to click to see the answer. You should also look into the .focus() method and possibly try to change focus to another element on the page. If none of this is working, it is probably some quirk with jQuery. I would suggest trying to selct the element this way:
document.querySelector(".btn").onmouseup = function(){
this.blur();
});
or:
document.querySelector(".btn").onmouseup = function(){
document.body.focus();
});

manually create spinning activity indicators

I apologize if this question is answered somewhere, but I couldn't find it.
I am working on editable javascript grid for MS Dynamics CRM and I am trying to display loading screen when user clicks "Save" button on the grid (the loading spinner should only be covering my grid - which is actually a HTML web resource displayed inside the CRM window). It takes about 2-5 seconds until CRM system saves the data and reloads my grid. So I want to display the loading screen during that time.
I found spin.js http://spin.js.org/ and it seems that it can be easily implemented but I am failing to realize on what event should I display the loading screen?
Basically, I have a table and when user clicks "Save" or "Delete" button, I wish to show that there is something going on under the hood.
Thank you very much for you time and help!
It sounds like you know what you want to call from spin.js, you're just trying to figure out where to call it from. You can try adding this to your javascript, where "#saveButton" and "#deleteButton" are the css identifiers for the buttons you want to fire the script off of.
$("#saveButton").click(function(){
displayLoadingPage();
});
$("#deleteButton").click(function(){
displayLoadingPage();
});
function displayLoadingPage() {
//call your spin.js code here.
}
Let me know if this answers what you were getting at.
I know you have got your answer but I think you can do it using vanilla JS code rather than using a library like spin.js
All you need is :
1) A div which is hidden on page load covering your table with spinner aligned center in it
2) On Save/Delete button click you can just make the div visible.
3) Hide the div again once you receive response from the rest api that saves or delete the data.
Below is the HTML:
<div class="container">
<div id="loading" class="loading" onClick="hideSpinner()">
Loading…
</div>
<input type="button" value="save" / id="saveBtn" onClick="showSpinner()">
</div>
JS Code:
var loadingDiv = document.getElementById('loading');
function showSpinner() {
loadingDiv.style.visibility = 'visible';
}
function hideSpinner() {
loadingDiv.style.visibility = 'hidden';
}
Here is a demo : http://codepen.io/AshutoshD/pen/dMEGqM
Click anywhere on the overlay to close it.
I have used the overlay that #MattIn4D has created here

Chat app Scrollable div or Iframe

What is the advised method to make a chat window scrollable, using an iframe or a scrollable div? What are the pros&cons of the two techniques? Which would you opt for and why?
Thanks
You can create a script that will embed a chat into a third-party website creating both <div> or <iframe>
The main interesting differences
iframe
Code: All user events (clicks, key events, hovers etc) are handlable exclusively from your external chat app page. Without a complicated API the user will not be able to easily modify or target desired events to suit their needs (Why should they after all). The sensitive backend code and logic can stay hidden on your side.
Styling: Your chat app will look exactly like you defined it. With an extended API the user will only be able to select some predefined styles. (I personally hate that.) So more coding for you.
Uses Mostly used by free chat apps where they force the app to be just the way they want it to be, preventing custom styles and possibly the removal of the App logo, link to the from site, or some random ads. Also used if you want to provide the data storage on your side, or provide silent application updates.
Scroll and heights are unaware of the surrounding items which ends mostly having an API where the user chooses some predefined chat heights.
DIV
Code: All user events (clicks, key events, hovers etc) are easily accessible and modifiable to the programmer. You can still have a nice plugin / API that will simplify customizations to the user.
Styling: The DIVs being rendered inside the user page will inherit that page styles.
The good part it that the chat app will have a design that suits perfectly the page design.
The hard part is that in your CSS you'll have to probably prevent some chat sensitive styles to be overwritten by the host page styles. Be careful.
Uses: people are gonna love it. If you want users to keep your link or logo you can ask them to keep the copyright or the link. You cannot count that this will happen. If you sell your app, or you just don't care, than I find this use the proper one.
Scroll and heights of chat elements are aware of the surrounding document. My suggestion here is to create a fluid chat app using %. That way your app will fit inside every container, and if it's a fluid page... more love for you.
So even if I would personally choose the <div> one, it's totally up to your needs.
Regarding scrollability I've created a nice UI technique:
Create a variable-flag that will register if the scrollable area is hovered
after you ping the server for the new message, run a function that will scroll the area to bottom
if the scrollable area is hovered means that the user is reading old chats
on mouseleave = scroll automatically the chat to the bottom (last conversation)
See it in action here
HTML:
<div class="chat">
<div class="messages">
<div>Old message</div>
</div>
<textarea></textarea>
<button>Post</button>
</div>
BASIC CSS (more CSS in the demo link):
.chat{
position:relative;
margin:0 auto;
width:300px;
overflow:hidden;
}
.chat .messages{
width:100%;
height:300px;
overflow:hidden;
}
.chat .messages:hover{
overflow-y:scroll;
}
.chat .messages > div{
padding:15px;
border-bottom:1px dashed #999;
}
jQuery:
var $chat = $('.chat'),
$printer = $('.messages', $chat),
$textArea = $('textarea', $chat),
$postBtn = $('button', $chat),
printerH = $printer.innerHeight(),
preventNewScroll = false;
//// SCROLL BOTTOM
function scrollBottom(){
if(!preventNewScroll){ // if mouse is not over printer
$printer.stop().animate( {scrollTop: $printer[0].scrollHeight - printerH }, 600); // SET SCROLLER TO BOTTOM
}
}
scrollBottom(); // DO IMMEDIATELY
function postMessage(e){
// on Post click or 'enter' but allow new lines using shift+enter
if(e.type=='click' || (e.which==13 && !e.shiftKey)){
e.preventDefault();
var msg = $textArea.val(); // not empty / space
if($.trim(msg)){
$printer.append('<div>'+ msg.replace(/\n/g,'<br>') +'</div>');
$textArea[0].value=''; // CLEAR TEXTAREA
scrollBottom(); // DO ON POST
// HERE Use AJAX to post msg to PHP
}
}
}
//// PREVENT SCROLL TO BOTTOM WHILE READING OLD MESSAGES
$printer.hover(function( e ) {
preventNewScroll = e.type=='mouseenter' ? true : false ;
if(!preventNewScroll){ scrollBottom(); } // On mouseleave go to bottom
});
$postBtn.click(postMessage);
$textArea.keyup(postMessage);
//// TEST ONLY - SIMULATE NEW MESSAGES
var i = 0;
intv = setInterval(function(){
$printer.append("<div>Message ... "+ (++i) +"</div>");
scrollBottom(); // DO ON NEW MESSAGE (AJAX)
},2000);
I will myself always go for a div for a chat application, Why?
Here is basic benefit. You can handle the events on a div, that you cannot handle using an iframe. You can try it for yourself, try to handle click, mouseover events inside an iframe, you won't get anything.
$('div').click(function () {
alert('Div was clicked!');
}
While iframe won't let you access events on the child elements of it.
While div will provide each and every event to the parent or even the js to handle and do the coding as necessary. For iframe you need to handle the events inside the iframe, lets say the page from where the iframe was loaded, its events are inside the code that was used to create it.
$('iframe').click(function () {
// code..this will execute when click is on iframe, not for a child
}
But you cannot do something as
$('iframe html body div').click(function () {
/* techniques for iframes are different and harder as
* compared to ones used for div, to get a child event
*/
})
But the elements inside the div can be embedded for your webpage. And you can always change its child or parent elements. So chat app will be better, if you can handle all the element events.
<div>
Some text
</div>
jQuery
$('div').on('event', function () { // on an event..
// so on, adding more and more event handlers and blah blah
})
In a div, you can just update the content using ajax request, and then add it to the div and you can also use jQuery API to scroll it. No matter how much page size, you can use % or exact place where to scroll to. So divs are simpler.
$('div').load('chat_page.php'); // load a page in the div
Or just update it using,
$.ajax({ // create ajax request
url: 'chat_message', // url
success: function (resp) { // if OK
$('div').html(resp); // update the page
}
});
Iframes are generally used to let others use your functionality, such as embedding chat application in a third party site, where you don't need them to edit or reuse your code. So you give them an iframe and a link.
Scolling thing was not understood by me! :( Sorry about that, I think I am going to write vague answer for that, so I will let that part go but this is how you can scroll the element
$('div').scrollTo(10); // scroll 10px down..
(You asked for browser support in comments) However, jQuery is supported cross-browser and cross platform. And the remaining part is HTML which is supported everywhere!
http://jquery.com/browser-support/ Here is a link to know the browser support
I prefer to use div as you can easily manage everything about it and it is easier to refresh, using less data for download for the server. Just a personal opinion.
PROS or DIV include less data, insert anywhere any time, and ability to easily use data for other tasks if needed on the page.
Pros of IFRAME easier to setup and code and easier ability to make it stand alone.
Cons of Iframe and it is harder to access data within and requires more code to do so if needed and cons of div are getting all the css and code right and inplace for the div and its parents and its children for it to flow correctly and nicely.

How can I have a textarea popup when the user clicks a button?

I've tried PopBox to have a textarea pop up, but the functionality of PopBox seems to be incompatible with the game system. (For example, I know for a fact that alert(); and prompt(); works in the html page testing, but does not happen at all in the actual game)
Currently the game has this confirm box system implemented. Is there a way to add a textarea to this?
If not, is there any other Jquery/JS tricks/plugins that will allow a textarea box to pop up when a button is clicked?
I'm no expert but I think this is possible:
<div id="textAreaDiv" style="visibility:hidden;"><textarea></textarea></div>
<input type="button" onClick="showTextArea()">
<input type="button" onClick="hideTextArea()">
<script>
function showTextArea() {
document.getElementById('textAreaDiv').style.visibility="visible";
}
function hideTextArea() {
document.getElementById('textAreaDiv').style.visibility="hidden";
}
</script>
OR...
To toggle the DIV with one button, you could do this:
<script>
function showHideTextarea() {
if (document.getElementById('textAreaDiv').style.visibility="hidden")
{
document.getElementById('textAreaDiv').style.visibility="visible";
}
else
{
document.getElementById('textAreaDiv').style.visibility="hidden";
}
}
</script>
And this doesn't need the JQuery library to use.
Hope it helps...
check this plugin
jAlert
very easy and clean to use, you can do whatever you want.
its easy to change the input by a textarea
in jquery.alerts.js file, search for 'prompt' case, and change the input by textarea.
i made this for me and have been working so far.
You can have a on the page, which inserts a textarea box when the button is clicked, something like this...
In original HTML page, stick a blank area, maybe reserving space like so
<div id="Input_Area">
<br>
<br>
</div>
Then, put an onClick event on your button which replaces the innerHTML with your textarea (or create a function that does it, and call it with your onClick event).
you can try jquery dialog http://jqueryui.it/demos/dialog.
This pops open an overlay and a dialog. You can customize this display and interaction to your hearts desire.

jQuery dialog call redirecting page

I'm using the jQuery dialog plugin.
The dialog div is set up (but not opened) on page load:
$(document).ready(function(){
$('#foo').dialog({autoOpen:false});
});
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
I have tried returning false:
Show dialogue box
But then the link doesn't respond at all when I click on it.
I know this must be to do with one of JavaScript's infamous subtleties but I can't work it out.
Can anyone help?
Then a hyperlink is supposed to open the dialog:
Show dialogue box
But this opens the dialog then a fraction later redirects to a page with the URL javascript:$('#foo').dialog('open');!
That shouldn't be happening. The pseudo-protocol javascript: doesn't involve a page load, and certainly not one via HTTP. I don't recommend it (I'd use jQuery's click handler instead), but it should work.
I have tried returning false:
...
But then the link doesn't respond at all when I click on it.
That also shouldn't be happening.
Your code as quoted is fine (works here, for instance: http://jsbin.com/inixa5), so the problem must lie in some other part of the page.
Update: Okay, that's weird, IE6 and IE7 didn't like that; I think it's because dialog returns a value. You can get around that either by wrapping up your call to open the dialog in a function and doesn't explicitly return anything:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
function showDialog(selector) {
$(selector).dialog('open');
}
</script>
Or (and this is mega-hacky) by making sure the last expression in the javascript: block is undefined:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
Or by using onclick:
Click Me
<script>
$("#foo").dialog({autoOpen: false});
</script>
But in any case, strongly recommend hooking things up with a DOM2 style event handler:
<a href="#" name='openSesame'>Click Me</a>
<script>
// This _can_ be immediately after the anchor, but I'd put it in
// a separate, since .js file for the page that you load just before
// the closing body tag.
$("#foo").dialog({autoOpen: false});
$("a[name=openSesame]").click(function() {
$("#foo").dialog('open');
return false;
});
</script>
Live example (Obviously, you can use any selector that makes sense, you don't have to give the anchor a name [or id].)
One of the nice things about this is that you can then have the anchor take the user somewhere meaningful and/or useful if JavaScript is disabled (something called progressive enhancement).
Change the link to:
<a href="javascript:void(0)" onclick="$('#foo').dialog('open')">
Show dialogue box
</a>
Best avoid putting javascript in the href.
Even better would be giving it a class and than adding a click event to it through jquery.

Categories

Resources