I was thinking about how the native functions in JavaScript work today, and I can across alert() and I figured it must use createElement() or make an element and use innerHTML, but I can't figure out the complete code it would need to create a popup element, and make two buttons, then return true or false based on the one click.
jowes said:
usually JS is async; why is alert special? how and why does it create UI elements in a different way from my own scripts?
Here's the code I have figured out:
function confirm(message) {
message = message.replace(/"\n"/g, "<br />")
createElement();
//The create Element is very complicated to create the text box including message. . .
//These two functions are tied to the button's onclick's.
function clickOkay() {
valueToReturn = true
return true;
}
function clickCancel() {
valueToReturn = true
return false;
}
//here, the user hits the button, and sets valueToReturn
return valueToReturn;
}
But I don't understand how it stops the background script, if accessable, or how createElement() works, (but thats a question for another time)
alert, confirm, and prompt are all DOM APIs that are implemented by the browser. They do not create DOM elements to represent them, and their functionality cannot be exactly recreated with JavaScript because you cannot force the JavaScript engine to wait for the user to click one of your buttons. You can only come close by requiring a callback that will contain the result of the dialog that you create.
function customConfirm(message, callback) {
message = message.replace(/"\n"/g, "<br />")
createElement();
//The create Element is very complicated to create the text box including message. . .
function clickOkay() {
callback(true);
}
function clickCancel() {
callback(false);
}
}
customConfirm("Hello World!", function (result) {
console.log(result);
});
The confirm()-function is a native function brought to you by every browser.
It is not created by using javascript. However if you want to reproduce that behaviour you go a way similar to this:
function myConfirm(text, cb){
// We need this later
var body = document.getElementsByTagName('body')[0];
// First we create a div which holds the alert and give it a class to style it with css
var overlay = document.createElement('div');
overlay.className = 'myConfirm';
// The box holds the content
var box = document.createElement('div');
var p = document.createElement('p');
p.appendChild(document.createTextNode(text));
// We append the text to the div
box.appendChild(p);
// Create yes and no button
var yesButton = document.createElement('button');
var noButton = document.createElement('button');
// Add text and events to the buttons
yesButton.appendChild(document.createTextNode('Yes'));
yesButton.addEventListener('click', function(){ cb(true); body.removeChild(overlay); }, false);
noButton.appendChild(document.createTextNode('No'));
noButton.addEventListener('click', function(){ cb(false); body.removeChild(overlay); }, false);
// Append the buttons to the box
box.appendChild(yesButton);
box.appendChild(noButton);
// Append the box to the Overlay
overlay.appendChild(box)
// insert the Overlay with box into the dom
body.appendChild(overlay);
}
myConfirm('Hello there!', function(value){ console.log(value); });
.myConfirm{
position:fixed;
width:100%;
height:100%;
background:rgba(0,0,0,0.05);
}
.myConfirm>div{
width:200px;
margin:10% auto;
padding:10px 20px;
border:1px solid black;
background:#ccc;
}
.myConfirm div p{
text-align:center;
}
.myConfirm div button{
width:40%;
margin:0 5%;
}
This could be an implementation for a self-made alert-box.
Note that the native alert is a synchronous-function. That means the browser stops the JavasScript-engine until the alert-box is closed. You cant clone that behavior but at least you can give the function a callback which is called, when one of the buttons is clicked. In this case the callback just logs the value to the console.
Hope I could help here!
UPDATE to the updated question
Back in the days when JavaScript was new confirm was a valid way to ask the user for a specific value. confirm, prompt and alert are special functions from these days which behave completely different than normal functions since they break the JavaScript-"flow".
When you ask why: Well - maybe it was a nice to have-feature back in these days. Note that in earlier versions alert looked like a system-message (in IE it still does). At least in Firefox you can nowadays interact normally with your browser even if alert is called.
That's why it is merely used for debugging only today (and even here console.log is the better choice).
I am pretty sure that today (in FF) the alert is rendered with browser-intern html and CSS, too.
Related
I am new to JQuery and web development in general and hence facing a troubling issue during development. My website interface looks like below:
When a user clicks on any checkbox (for referral purposes, I have selected the box above 'chk2') and then clicks on the 'Show Evidence' button (box 2 in the image), I want the user to be able to highlight portions of the article displayed in the adjacent iframe. I am using a text highlighter Jquery plugin I found on the web. The code for the click event of the 'Show Evidence' button looks like:
$('.show_evidence').click(function(event){
var iframe = document.getElementById('myiFrame');
var hltr = new TextHighlighter(iframe.contentDocument.body);
hltr.setColor("yellow");
});
The above code works fine.
Now, I want to set the highlight color (i.e. hltr.setColor("blue")) to blue when the user clicks on the checkbox 'Unselect' (box 3 in the image). For that I need to be able to access the 'hltr' object I have defined above (i.e. inside the 'click' event handler for '.show_evidence'). Also I want to set the highlight color back to 'yellow' when the user unchecks the 'Unselect' checkbox.
$(".unselect").change(function() {
if(this.checked) {
//Something like - hltr.setColor("blue");
}
else {
// Something like - hltr.setColor("yellow");
}
});
Finally, I also want to unset or undefine the object 'hltr' when the user clicks on the link 'Hide Datums' (box 1 in the image).
So my question is how do I access the hltr object inside the event handlers for .Unselect and the 'Hide Datums' link.
After a lot of stackoverflow surfing, I found that I could use external variables but I am not sure whether that will work for objects. Also, is there a universally recommended design that I should use or follow? What is the best way to achieve what I want?
Looking forward to your suggestions. Please help!
Regards,
Saswati
One way you can go about is extract the lines of code which does the element selection to a separate method.
var hltr;
function getBodyElementOfIframe() {
var iframe = document.getElementById('myiFrame');
if(!hltr) {
hltr = new TextHighlighter(iframe.contentDocument.body);
}
return hltr;
}
Call that method where you want to access the element and then set the color.
$(".unselect").change(function() {
var hltr = getBodyElementOfIframe();
if(this.checked) {
hltr.setColor("blue");
}
else {
hltr.setColor("yellow");
}
});
There are a number of ways to solve it, but one simple way to do it would be to move the variable outside the scope of the method so that it is accessible through out.
I would put it inside on ready.
$(document).ready(function () {
var hltr = {};
$('.show_evidence').click(function(event){
var iframe = document.getElementById('myiFrame');
hltr = new TextHighlighter(iframe.contentDocument.body);
hltr.setColor("yellow");
});
$(".unselect").change(function() {
if(this.checked) {
//Something like - hltr.setColor("blue");
}
else {
// Something like - hltr.setColor("yellow");
}
});
})();
If you need the variable inside several functions, declare it outside of all of them.
$(function(){
var iframe = document.getElementById('myiFrame');
var hltr = new TextHighlighter(iframe.contentDocument.body);
$('.show_evidence').click(function(event){
hltr.setColor("yellow");
});
});
When your event handlers fire, they'll be updating this var and it will be accessible to the next handler called.
While I've done some Javascript coding, I consider myself a more novice, Frankenstein-type coder, basically cutting and pasting with trial and error to see if I can get something to work...just a heads up on my honest assessment of my experience level.
I've got a unique thing I'm developing for, and hoping to get some help with Javascript. Here's what I'm trying / need to do: for a webpage based kiosk presentation, I'm using one HTML webpage, but with multiple sections whose visibility toggles on/off based on a Javascript I currently have that works fine. (I don't want to / can't use regular HTML pages with links because of how it ends up running).
The only problem with the above issue is that there's no easy way to create a 'back' or 'previous page' link for an end page that may have multiple ways to get to it. It won't 'know' where the user came from.
So here's what I'd like to do: pass 2 variables through my OnClick javascript function, the DIV name that needs to toggle on/off ... AND a 2nd variable of the current visible DIV name so that the next DIV that toggles on can 'remember' what the previous (and now invisible) DIV was so that there can be an accurate 'back' button.
Here's some sample code:
Each DIV section that turns on an off is setup like this:
<div id="sectionName" class="content">
</div>
These DIVs have buttons/links that are setup like this:
These run a Javacript:
function toggleVisibility(selectedTab) {
var content = document.getElementsByClassName('content');
for(var i=0; i<content.length; i++) {
if(content[i].id == selectedTab) {
content[i].style.display = 'block';
} else {
content[i].style.display = 'none';
}
}
}
So what I'm hoping is that there is a way to do something like this:
So that when that is clicked, the next DIV that turns on could also include a Javascript generated link based on that passed variable, something like:
Previous<br>Menu
I'm aware that Javascript toggling of DIVs on and off may not allow the generation of a dynamic Javascript link like the one I'm describing above, so I'm throwing this out there for some help from other, far more experienced programmers. Ideally, I'd like to try and fit everything into what I've created so far, so I don't have to start over from scratch. Any ideas?
Please reference this sample page:
www.gs3creative.com/test/
You could use location hashes (mypage.html#mydivid) and then use history.back() to handle 'back' navigation.
To stitch up the div's showing on the correct hash value....
var oldHash = '';
// fires when the hash changes
function hash_changed() {
var hash = location.hash.replace('#', ''); // get the div ID
var div = document.getElementById(hash); // find the content div on the page
var allDivs = document.getElementByClassName('content'); // get all of the content divs
// hide all the content divs
for (var i = 0; i < allDivs.length; i++) {
var thisDiv = allDivs[i];
thisDiv.style.display = 'none';
}
// only show the right one
div.style.display = 'block';
}
// this triggers the event
setInterval(function() {
// if the hash has changed, fire the function
if (oldHash != location.hash) {
oldHash = location.hash;
hash_changed();
}
}, 100); // call every 100 ms so that there is no lag
So if you set the navigation to 'mypage.html#sectionName' it would hide all other div's of the class 'content' and then only show the div with the ID of 'sectionName'.
An easy solution for me would be to render two content pages on a HTML page and show and hide content when needed from a onlick handler via javascript in your CSS add a class:
function showDiv() {
document.getElementById("theObject").className = "visible";
}
CSS:
// Switch between the content adding the classes and removing the old class
.visible{
display:none;
}
.show{
display:block;
}
Another solution using sessions "php" via javascript to hold the variables with in statements.
<?php if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['user_is where_variable'] = "im on page div 1";
}
This could also be done through js anyways.
javascript have a conditional statement using your $_SESSION vars;
if (variable == "im on page div 1" ){
// your functions
}else if ( variable == "im on page div 1"){
// another function
}
Create your click handler to update the variables in the session.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create TRULY modal alerts/confirms in Javascript?
TL;DR: I've overridden the default alert() function with a custom HTML based one. I want the new dialogue to still block execution, and get the buttons within my dialogue to return true or false from the call to alert() to use in logic (and continue execution).
I'm trying to implement a custom alert box, which replaces the default browser alert with a nicely themed box with the same (or similar) functionality.
I've read this question, and I'm using the solution given in this answer (to the same question). What I want to do now is get my overridden alert to return a true or false value for use in if() statements, depending on whether OK or Cancel was clicked:
if(alert('Confirm?') {
// Do stuff
}
However, due to having custom HTML instead of a normal alert I can't do this for two reasons:
I can't return a value from the buttons in the replacement dialogue (click events bound with $.on()) because I have no idea how to.
I can't block program flow with this alert, as far as I know.
I've bound $.on() events to the Cancel and OK buttons in the replacement dialogue which hide the box. These work fine, but the problem I have now is returning a value when a button is clicked, so that execution will halt until an action is taken by the user.
HTML:
<div class="alert background"></div>
<div class="alert box">
<div class="message"></div>
<hr>
<div class="buttons">
<input type="button" name="cancel" value="Cancel">
<input type="button" name="confirm" value="OK">
</div>
</div>
Current JavaScript: (pretty much a carbon copy of the answer in my linked question)
(function () {
nalert = window.alert;
Type = {
native: 'native',
custom: 'custom'
};
})();
(function (proxy) {
proxy.alert = function () {
var message = (!arguments[0]) ? 'null' : arguments[0];
var type = (!arguments[1]) ? '' : arguments[1];
if (type && type == 'native') {
nalert(message);
} else {
// Custom alert box code
console.log(message);
}
};
})(this);
Ideally, I want to be able to put something like this in the // Custom alert box code part:
$('.alert.box input[name="confirm"]').on('click', function() {
// Hide dialogue box - I can do this already
// *** Return `true` or other truthy value from
// alert for use in `if()` statements
});
So that when the OK or Cancel button is clicked, it removes the custom alert box and returns a true or false value from the call to alert(). I can already remove the alert with $.fadeOut() and $.remove(), that's easy. What isn't is knowing how to get the button click events to get alert() (overridden) to return something.
I've tried to be as clear as I can, but I may have missed something out. Please let me know if I have.
The example below shows an approach to creating a custom alert and handling the outcome of the user selection
/*
message = String describing the alert
successCallBack = callback function for when the user selects yes
*/
function exampleAlert(message, successCallback)
{
/*Alert box object*/
var alertBox = document.createElement("div");
/*Alert message*/
var msg = document.createElement("div");
msg.innerHTML = message;
/*Yes and no buttons
The buttons in this example have been defined as div containers to accentuate the customisability expected by the thread starter*/
var btnYes = document.createElement("div");
btnYes.innerHTML= "Yes";
/*Both yes and no buttons should destroy the alert box by default, however the yes button will additionally call the successCallback function*/
btnYes.onclick = function(){ $(this.parentNode).remove();successCallback();}
var btnNo = document.createElement("div");
btnNo.innerHTML= "No"
btnNo.onclick = function(){ $(this.parentNode).remove();}
/*Append alert box to the current document body*/
$(alertBox).append(msg, btnYes, btnNo).appendTo("body");
}
function test()
{
alert("Example alert is working, don't use this test as a replacement test - horrible recursion!")
}
exampleAlert("shoe", test)
This is fairly basic and doesn't allow for additional data to be supplied to the callback function and for that reason is not ideal for production however jQuery's .bind() and similar methods allow for data to be associated with the callback method
It's worth commenting that while the above demonstrates a full implementation of the problem, there are in fact only two lines that actually matter.
btnYes.onclick...
btnNo.onclick...
Since we're achieving the desired result by binding onclick events for true and false respectively, everything else is there to paint the picture.
With that in mind it is possible to effectively turn any container object with at least one sibling into an alert box for eaxmple:
<!-- Example html -->
<div id='a'>
<ul>
<ul>
<li>Something</li>
<li>Something Else</li>
<li id='yesIdentifier'>Something not necessarily suggesting a trigger?</li>
</ul>
</ul>
</div>
As long as your yes / no (if no exists) options destroy the appropriate container a converting a container into an alert box can be handled in a couple of lines of code.
$('#yesIdentifier', '#a').click(
function(){ someCallback(); $(this).closest('#a').remove()});
Neither of the above are exemplary models for implementation but should provide some ideas on how to go about the task.
Finally... do you really need to replace the native alert method? That is, either you're writing the alert calls, in which case you'd know to use your custom method, or you're overwriting default behaviour that you can't guarantee the other developers will be aware of.
Overall recommendation:
I feel the best approach to this would be to create a jQuery plugin which creates the custom alerts on the fly and track callbacks, results and what not within the plugin.
SOliver.
Why don't you just use a confirm box like so.
var c = confirm('Confirm?');
if(c)
{
// Yes clicked
}
else
{
// No clicked
}
Or you could use jQuery UI's dialog confirmation box.
http://jqueryui.com/demos/dialog/#modal-confirmation
I am trying to use setTimer to animate a slide show using straightforward jQuery. I provide the user with a button (in the form of a "DIV" with a button background image) that he clicks to start the show and which then turns into a pause button. The slides are supposed to change every 3 seconds. Here is the relevant code:
playLink = $('<div id="lbPlayLink" />').click(function(){
$(playLink).hide();
$(pauseLink).show();
slideInterval = setInterval(function(){next()}, 3000)
})[0];
pauseLink = $('<div id="lbPauseLink" />').click(function(){
$(playLink).show();
$(pauseLink).hide();
clearInterval(slideInterval);
}).hide()[0];
The next() function call does the work of replacing the slide with the next one. I have checked out this function and it works perfectly if I call it directly (synchronously), however, when it gets called asynchronously by the setInterval, it works fine the first time (3 seconds after I click on the button), but is never called again, even though it should be called 3 seconds later. I know it's never called as I put an "alert" call at the beginning and end of the function.
If I replace the next() call in the setInterval with alert('test') then I can see the setInterval is doing what it is supposed to. I can't for the life of me see why alert() is OK but next() isn't, unless it has something to do with "scope" of functions, but in that case why does it work the first time?
I've tried debugging the code with firebug, but it can't really help with timeout functions like this. Neither Firefox nor IE8 show any error messages.
I've looked through the various posts here and elsewhere on setInterval, but can't see anything relevant that I haven't tried already. I've been experimenting now for about 3 hours and it's doing my head in. Can anyone suggest what I can try next?
Hmm, I don't like the way you wrote the code, it is not very readable, I would rather suggest something like the following (not tested yet, not sure if it works):
The CSS:
#slides{
/* So you can position your elements under the div#slides */
position: relative;
}
.button {
width: 50px;
height: 10px;
/* So you can position your button anywhere you like */
position: absolute;
bottom: 10px;
right: 10px;
}
.play {
background:url(..) no-repeat;
}
.pause {
background:url(..) no-repeat;
}
The HTML consist of the parent slides holding everything relating to slides, and the controller, basically holds your button image.
<div id="slides">
<div id="controller" class="button play"></div>
</div>
The code:
(function() {
//Let's wrap everything in an anonymous function, so to avoid variable confusion
function next() {
//Assume this is your code doing the sliding. I don't touch
}
var invt;
function play() {
//Always clear interval first before play
if (invt) clearInterval(invt);
invt = setInterval(function() {
next();
}, 3000);
}
function pause() {
if (invt) clearInterval(invt);
}
$(document).ready(function() {
$('#controller').click(function() {
//It's not playing so it has the play class
if ($(this).hasClass('play')) {
$(this).removeClass('play').addClass('pause');
pause();
}else{
$(this).removeClass('pause').addClass('play');
play();
}
});
});
})();
change this line on both:
$('<div id="lbPlayLink" />').click(function(){
to:
$('<div id="lbPlayLink" />').live("click", function(){
To clarify how I solved the problem:
I took onboard Ivo's suggestion to have a single button (though in the form of a "DIV" element rather than a "BUTTON") and change the class of this button between "lbPlay" and "lbPause" to change the background image and trigger the correct action.
My main problem was that I was unknowingly setting the event on this button multiple times and I believe this is what was causing the strange behaviour.
I got round it by putting the return code from the "setInterval" call into a variable ("ppHandler") attached to the DIV, using the jQuery "data" method.
The new code is:
if (typeof($(playPauseLink).data('ppHandler')) == 'undefined'){
$(playPauseLink).click(function(){
var $this = $(this);
if ($this.hasClass('lbPlay')) {
if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
$this.data('ppHandler', setInterval(function(){next();}, slideInterval*1000));
$this.removeClass('lbPlay').addClass('lbPause');
} else {
if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
$this.data({ppHandler: -1});
$this.removeClass('lbPause').addClass('lbPlay');
}
});
Thanks to all who responded. To see the final result go to "www.trips.elusien.co.uk" and click on the "slimbox examples" link and go to "example 9".
Good afternoon all
Here is my scenario:
I have user controls within a master page and within a user control, I may have an update panel. I have the following bit of code I place within a usercontrol that maintains various control styling during partial postback i.e. those controls affected within by an asp update panel.
function pageLoad(sender, args) {
if (args.get_isPartialLoad()) {
$("select, span, input").uniform();
Indeed, when an update panel does its thing, the Fancy Dan styling is maintained.
However, I have one gripe - when a 'large' partial postback occurs, occassionally you'll see the default, generic control styling reappear breifly and then the uniform kicks in to reapply the new fancy styles.
Is there any way I can avoid seeing the nasty old, default, bland stylings?
Any suggestions greatly appreciated.
Check out working with PageManagerRequests: MSDN Working With PageRequestManager
Sys.WebForms.PageLoadingEventArgs Class
Sys.WebForms.PageRequestManager pageLoading Event
$(function() {
Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(beautify);
});
function beautify(sender, eventArgs) {
// If we have event args
if (eventArgs != null) {
// for each panel that is being updated, update the html by adding color red
// to select, span, input elements
// must remember to call .html() to put html back into the panelsUpdating[i], otherwise it puts in the jQuery Object
for (var i = 0; i < eventArgs.get_panelsUpdating().length; i++) {
//My test code
//var content = eventArgs._panelsUpdating[i].outerHTML;
//var jContent = $(content);
//$("input", jContent).css("color", "red");
//jContent = $('<div>').append(jContent)
//var jContentToContent = jContent.html();
//alert(jContentToContent);
//eventArgs._panelsUpdating[i].outerHTML = jContentToContent;
//Cleaned up
var jContent = $(eventArgs._panelsUpdating[i].outerHTML);
$("select, span, input", jContent).uniform();
jContent = $('<div>').append(jContent);
eventArgs._panelsUpdating[i].outerHTML = jContent.html();
}
}
}
Edit: I think you understood that the issue was the elements were being placed into the DOM (and therefore painted) before your javascript had a chance to make them uniform(). This intercepts the UpdatePanel and uniform()'s the code prior to it inserted into the DOM
Edit 2 Alright, I've updated it a bunch, I tested this with my test code there and then included the code you're likely to add. Also, I took a short cut in eventArgs._panelsUpdating - i should really be using the get and set functions, but this works.