i have a javascript prompt like the following and i would like to bring the prompt center of the screen. How to do this in using javascript?
function showUpdate() {
var x;
var name=prompt("Please enter your name","");
if ( name != null ) {
x="Hello " + name + "! How are you today?";
alert("Input : " + name );
}
}
And this is how i call this :
<a onclick = "showUpdate() " style="vertical-align: middle;" class="parent" href=""><span>5. Missed P/U Comments</span></a>
it works find excepts the prompt goes to the left corner in IE and center in Firefox
but i need to the same solution to work in both the browsers.
The prompt (and alert) popups are implemented differently depending on the browser you're using. This is because the popups are browser functionalities, they aren't JavaScript objects or anything like that. (Just like the console is different for each browser, it depends on the implementation.)
If you really want your prompts to be positioned / styled consistently, you're going to have to build your own prompt.
The easy way out would be to use a library like jQueryUI.
On the other hand, you can just build it yourself:
document.getElementById('showPromptButton').addEventListener('click', showSprompt);
document.getElementById('promptButton').addEventListener('click', submitPrompt);
var prompt = document.getElementById('myPrompt');
var promptAnswer = document.getElementById('promptAnswer');
function showSprompt() {
promptAnswer.value = ''; // Reset the prompt's answer
document.getElementById('promptQuestion').innerText = "What's your question?"; // set the prompt's question
prompt.style.display = 'block'; // Show the prompt
}
function submitPrompt() {
var answer = promptAnswer.value; // Get the answer
prompt.style.display = 'none'; // Hide the prompt
console.log(answer);
}
#myPrompt{
display:none;
/* Style your prompt here. */
}
<input id="showPromptButton" type="button" value="Show Prompt" />
<div id="myPrompt" class="proptDiv">
<span id="promptQuestion"></span>
<input id="promptAnswer" type="text" />
<input id="promptButton" type="button" value="Submit" />
</div>
You cannot customize or postion the default javascript prompt. Check this SO answer for workarounds.
How to customize the JavaScript prompt?
Prompts, alerts, and confirms are basic functions that each browser has its own way of displaying to the user. There's really no reason that you should want to customize these functions, either.
If you really want advanced functionality and complete customization, you'll have to make your own custom alert. You can do this in one of several ways. One out of two options that I'll suggest is creating two divs (one that fades out the rest of the page and one that appears like an alert) in Javascript and use those as a pseudo-prompt. The second is to create a new window, remove a lot of its functionality and change some HTML on the newly opened page to make it look somewhat like an alert.
I feel like the last one is really overdoing it though. If you want a prompt, they're ugly... Otherwise, you'll need to make something yourself with a positioned div and faded background.
...but i need to the same solution to work in both the browsers.
prompt (and its cousin alert) are very outdated. You have no control over their appearance or position. It's mostly best to avoid them.
Instead, you can do a popup message using an absolutely-positioned div (or any other block element), which not only gives you full control over its position, but full styling as well. If you look around, you'll find dozens of examples of doing this, and toolkits for it, there's no need to roll your own unless you really want to.
Regardless which way you end up doing it, your logic using it will have to change, because prompt is synchronous (all script on the page comes to a screeching halt and waits for the prompt), whereas modern ways of doing this are asynchronous (event-oriented). So for instance, your new code for using the popup might look like this:
function showUpdate() {
popup("Please enter your name","", function(name) {
if (name!=null)
{
x="Hello " + name + "! How are you today?";
alert("Input : "+name); // <== I left this one alone, looks like debugging
}
});
}
NOTE: The method window.showModalDialog() is obsolete and is not
supported in modern browsers. Please do not use it.
You cannot reposition window.alert(), but you can do so with window.showModalDialog() as described in this page: http://bytes.com/topic/javascript/answers/849283-change-position-alert-possible
https://developer.mozilla.org/en-US/docs/DOM/window.showModalDialog
Related
I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>
First of all, I am not a programmer. I do not know Javascript at all. I'm trying to create a Chrome extension that modifies my browser tab's title, by taking a specific string on a webpage. I know how to create Chrome extensions (just barely) and I just need to modify the Javascript to do what I want (which I do not know how).
I found the following script online and am trying to modify it but can't figure out how to get it working. Here is the script:
https://pastebin.com/dY1LSdjT
// Fire this event any time the mouse is moving. Sucks for performance, but it's a better experience
document.addEventListener("mousemove", function() {
// This will get us the banner
let bannerTextElements = document.getElementsByClassName("dijitReset dijitInputField dijitInputContainer");
console.log(bannerTextElements);
console.log(bannerTextElements[0]);
if (bannerTextElements[0]) {
console.log("ok!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(bannerTextElements[0].innerHTML);
// This will get us the text
let bannerTextLine = bannerTextElements[0].getElementsByClassName("dijitReset dijitInputInner");
console.log(bannerTextLine);
document.title = bannerTextLine[0].innerHTML
}
}, false);
And here's the website viewed in developer mode. I would like to get the text "blahhhh" and use that for the title of my browser tab.
Below is a different webpage and the difference here is that the "div class" names will change. The numbers in those class will change to different numbers, but the structure and the overall name remains the same. For example, "ms-Button-label label-549" may change to "ms-Button-label label-640". This happens whenever you refresh the page. I found that the "viewport" id name doesn't change though, so I think if we can use that as a reference and then just look at the nested div classes and reference them and extract the value (in this case Crystal Mountain).
Fixing your code
You got like 95% of everything you need.
The one thing you are missing right now is that the fact that an input element does not posses an "innerHTML" (That is why it isn't closed like this: <input>renderedText</input>). Instead you want to check for it's value:
document.title = bannerTextLine[0].value;
Some Improvements:
Search by ID
You have a well defined input which can be more easily obtained by looking it up using the id:
let bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
End result:
const bannerTextLine = document.getElementById('lanDeviceIndex_searchBox');
bannerTextLine.addEventListener("blur", function() {
if (bannerTextLine != null) {
document.title = bannerTextLine.value;
}
});
This is the entire JS code. Note that I changed the event to blur which activates when the form is left, this should be optimal for your case.
Ok, first off. No jquery, no ajax, just pure javascript.
I have the following code on a page called text.html.
<html><body>
<script>
function live(ID,txt2) {
var a = document.getElementById(ID);
a.innerHTML = (txt2);
}
setInterval(live, 250);
a.innerHTML =(txt2);
</script>
<div id="txt1">Live</div><p />
</body></html>
I have the following code on live2.html
<html>
<body>
<p />
<iframe width="400" height="50" src="text.html" name="frameA" id="frameA"></iframe><p />
<input type="button" value="Live" onClick="document.getElementById('frameA').contentWindow.live('txt1','L I V E')">
<input type="button" value="Rebroadcast" onClick="document.getElementById('frameA').contentWindow.live('txt1','Rebroadcast')"><br />
text
</body>
</html>
The current code works exactly as I wanted it to by updating the information in an iframe. My issue is this. If someone visits text.html directly, I want them to be able to see whatever I've changed that document to.
Example:
I click on a button and the text in the iframe now says rebroadcast.
Someone else visits text.html and they also see rebroadcast. If while they are looking at text.html, I hit the live button, the text.html page will update with the word live.
I can do PHP scripting on this as well. I have tried jquery and have issues with getting it to work correctly and I don't really have the knowledge or access to implement much of anything else.
This is an on-going project. The end result, I hope, will be an iframe that I can update while not actually being on the same page that the frame is located on. (same domain tho) The content will be anything from images, to youtube embeds and pictures. I'm trying to get a more comprehensive idea of how this language works and that's why I'm taking it one step at a time. I have no issue with visiting tutorials or looking at pre-made solutions. Thanks for your help. :)
I think I'm probably missing something. Users will always see the text "Live" because that's what's hard-coded in text.html. It doesn't matter if you change the text through JavaScript since it will only affect the browser that you're seeing. You need to save it to a persistence storage (ie. database) and dynamically display it on the page.
live2.html can use AJAX to send the changes to the server, which can then update live.html. But this is a poor way to do it, since it means that the contents of live.html are updated outside of your version control and/or content management system. It's better to use a real database and generate the page dynamically, as suke said.
First off this is what happens when someone learning programming languages doesn't fully comprehend what a language can and can't do. The original idea was to let a specific group of people know when it was a re-broadcast or when the show was live. I wanted the control of when to change that information to only be available to an admin of sorts. In the end the entire idea got scrapped and entirely impractical. The solution, essentially, doesn't exist in the context of the way I wanted to accomplish this. Years later...
The solution is to have live and rebroadcast inside div tags with CSS. Then use a JavaScript function to change the attributes of the divs to either be hidden or shown. The button or or link would need to exist on the same page as the live or rebroadcast text. This would also mean that there is no need for a separate frame. To have this element controlled from outside the page it's on could only be done by storing a value somewhere else and having that value periodically checked.
JSFiddle
The Script:
var x = document.getElementById("txt1");
var y = document.getElementById("txt2");
function htext() {
x.style.visibility = 'visible';
y.style.visibility = 'hidden';
}
function stext() {
x.style.visibility = 'hidden';
y.style.visibility = 'visible';
}
function ctext() {
var z = getComputedStyle(x).getPropertyValue("visibility");
if (z != 'hidden') {
stext();
} else if (z != 'visible') {
htext();
}
}
The CSS:
#txt1 {
visibility: hidden;
margin-left:0px;
}
#txt2 {
visibility:visible;
margin-left:0px;
}
The HTML:
<span id="txt1">Live</span>
<span id="txt2">Rebroadcast</span>
<br />
click
To be honest. I'm not entirely sure of the programming needed to store information somewhere else and have a check to see if certain conditions are true. The program above will essentially hide and show a div. I could probably go a step further and use JQuery to create and remove the actual div itself. In the end this is essentially close to the solution I ended up using and then later on discarding and giving up on the project.
I have some crazy app done almost 100% by manipulating the DOM and I find myself in the unfortunate position of changing something in it. As there are probably around 100 different scripts that do God knows what, I have no clue in which file should I look to make my changes. So, I want to ask, is there a way (using Firebug maybe or something similar) to know where a specific piece of html was generated? I'm a C developer, so I'm not very good at this, it drives me crazy.
Are all the elements added at the page load, or partially in the response to the user input? (clicking etc.)
for stuff added with the response to your actions, you can use Firebug's "Break On Next" button in the "Script" tab. To active BON you have to click it, or, in just-shipped Firebug 1.10.0a8, use keyboard shortcut ALT-CTRL-B (useful when you have event listeners bound to mouse movements). Then, when any piece of JS is going to be executed in reaction to your click etc., you will hit a breakpoint.
for stuff added at page load time, you may use the trick of extending the native functions (this might sound crazy - yeah it is, don't do it in production!) like appendChild, insertBefore, replaceChild. Just insert the appropriate code at the very top of your main HTML file, so all the code below will "see" the change.
Unfortunately, this does not work in Firefox due to a bug. But works in Opera and I guess in Chrome as well.
When you extend the native function, you can inject any code before really adding the node to the page. For instance, call console.log or create a breakpoint, to inspect the current page state. You can try playing with breakpoints to see the available variables properties inside those function to adjust what you push to console.log.
For this code:
<!doctype html>
<html>
<head>
<script type="text/javascript">
// this should work in Firefox but it does not -- https://bugzilla.mozilla.org/show_bug.cgi?id=618379
// works at least in Opera, probably Chrome too
Node.prototype._appendChild = Node.prototype.appendChild;
Node.prototype.appendChild = function(child) {
console.log("appending " + child + " to " + this);
return this._appendChild(child); // call the original function with the original parameters
}
// this works in Firefox
document._createElement = document.createElement;
document.createElement = function(tagName){
console.log("creating " + tagName);
return this._createElement(tagName);
}
</script>
</head>
<body>
<script type="text/javascript">
var p = document.createElement("p");
p.appendChild( document.createTextNode("abc"));
document.body.appendChild(p);
</script>
</body>
</html>
Opera outputs:
creating p appendChild.html:14
appending [object Text] to [object HTMLParagraphElement] appendChild.html:7
appending [object HTMLParagraphElement] to [object HTMLBodyElement] appendChild.html:7
To overcome the weakness of Firefox (that you can't override appendChild), you may use the trick: place the code below instead in the top of your HTML
<script>
Node.prototype._appendChild = function(child) {
console.log("appending " + child + " to " + this);
return this.appendChild(child)
};
</script>
and then, use Fiddler proxy by creating auto-responders (WMV tutorial, 9.9 MB) where you manually replace all calls to .appendChild with ._appendChild (you can use Notepad++ for "find replace in all opened files"). Creating auto-responders and hand-tampering requests can be mundane, but it's extremely powerful. To quickly create auto-responder rule, load the page when Fiddler is active, then drag'n'drop files as in the picture below. For each file, right click and choose "Generate File" from menu (this will put a file on the desktop) or create a file by yourself in different location. (it's good to open Fiddler-generated files and remove response headers from them; BTW "Generate file" puts real contents only if the response header was 200, so make sure to load the page with CTRL-F5 to skip the cache).
In Chrome you can inspect an element and right click on it. This menu gives you some options to break when something below the element is changed or when it's own attributes change. Maybe one of those breakpoints will find what you are looking for?
Assuming you've got access to the raw (hopefully un-minified/obfuscated) JS files, maybe just search them for text strings related to DOM manipulation and/or attributes of the node you're trying to find the creation of? I'd try things like "appendChild" "createElement" and the node's ID/class names.
You could also set break points all over the script files, and step through them as the page loads to help you narrow down where to look. Might help to start by just "pausing" the JS execution and stepping through from the very beginning.
If you can share the code (a link to the live site would do fine) I'd be happy to take a look.
If you are using the jQuery framework in your javascript to make the DOM changes then you may find the fireQuery plugin for FireBug in the firefox browser may get you the information you need.
Example:
It adds additional information to the standard HTML view by superimposing additional jquery element information to the display to provide a deeper insight into how your javascript is amending the page content.
I hope that helps you out.
I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>