JavaScript - Couple Of Very Basic Questions Do With Event Handling
Hi there,
I've been a web designer for a while and have always used basic javascript in my pages, but decided recently that I would get right into the nitty gritty, however I'm having a problem with some really basic code. Secondly, the book which I'm using is from 2005 and is extolling the virtues of event listeners and so on, is this still the accepted means of handling events? And thirdly, are there still chasms between the browsers in compatability in this area? I'm aware IE has become more and more compliant recently, is it still necessary to write code to cover different browsers or does it all pretty much work nowadays (besides older browsers)? So, to the code! Basically, the browser doesn't get into the function to display the alert(), and i'm not sure why. (Told you it was basic ) Code: <html> <head> <title>Javascript Testing</title> <script type="text/javascript"> <!-- function aKeyWasPressed(e){ alert('Sausages!'); } var textarea = document.getElementById('myta'); textarea.addEventListener('keyup', aKeyWasPressed, false); --> </script> </head> <body> <textarea id="myta"></textarea> </body> </html> Thanks! Similar Tutorialshey guys. got acouple questions for my website. im more of a html guy.. and i usually find my scripts online. i reeaaallly appreciate all answers! i have a box: <img id="imgSearch" src="" alt="Websites" /> <input type="button" value="Toggle Search" id="btnSearch" /> ^being the button to toggle between websites. basically i'd like this button to toggle between different websites when clicked. secondly: changing span tag colors html code: Traffic Light: <span id="trafficLight"></span> <input type="button" value="Prevent Accident" id="btnTraffic" /> i'd like to change the color of this span id by pressing the button. so in this case it would change red, yellow green and last: changing the font in a bold tag bold by pressing a button html code: (note, the font weight in normal in css for bold) <b>i want this bold when you hit the button!</b> <input type="button" value="Set Bold" id="btnBold" /> Hi I am new to Javascript. I am working in keyboard Event handling. i dont know how to handle multple keys pressed or sequence of keys pressed. Want to know more about key holding , key Listener. Hi, im sorta a newbie but have a few questions i cannot find online anywhere. By the way im trying to create a chrome extension . Its a fairly simple extension, all i want it to do is select a few buttons automatically when the page is loaded. Without me having to click anything. A bot persay. How to automatically select a button/drop down menu How to save a form How to submit a form to a website How it works if you dont get it? Selecting a certain size like S/M/L, color, or anything of that nature AUTOMATICALLY WITHOUT HAVING TO CLICK ANYTHING. Which then adds to my cart. Thats all i want it to really do. Thanks for reading. Hi forum, I am trying to attach an event to a dynamically produced button, and then use stopPropagation and preventDefault. Code: function chapter12_nodeOne() { //create an element var element = document.createElement('input'); //set some attributes element.setAttribute('type', 'button'); element.setAttribute('value', 'submit'); element.setAttribute('id', 'myBtn'); //appendd the element into a DIV document.getElementById('myDiv').appendChild(element); //uses EventUtil to attach an event listener EventUtil.addHandler(element, 'click', function() { alert('event attached'); }); var flag = confirm('prevent default behavior of button?'); if (flag) { var el = document.getElementById('myBtn');/////////////////////////(1) var ev = el.onclick; } } var EventUtil = { addHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.addEventListener) { element.addEventListener(type, handler, false); } //if user is browsing with IE else if (element.attachEvent) { element.attachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = handler; } }, removeHandler: function(element, type, handler) { //check if the element and the browser support DOM Level 2 event attachment //if the user is not browsing with IE if (element.removeEventListener) { element.removeEventListener(type, handler, false); } //if user is browsing with IE else if (element.detachEvent) { element.detachEvent("on" + type, handler); } //if user is using a browser that only supports DOM Level 0 event attachment else { element["on" + type] = null; } } }; But when debugging I see under el on the line marked with (1) that the onclick event is null. What am I doing wrong?! PS:the event is attached, when I click on the button I get an alert message is it possible to capture the control.event or element.event that was fired to invoke the onbeforeunload event. for example, if a button is clicked and it causes the onbeforeunload event to fire can i determine which button was clicked. thanks I'm doing an assignment and I'm trying to get these codes to work but nothing works. Can anyone help please? Code: <script type = "text/javaScript"> var animal = prompt("Please enter the name of an animal (elephant would be good!)",""); animal = animal.toUppercase(); if (animal="ELEPHANT") { alert ("Elephants are very large and also gentle."); alert ("Have you ever seen an elephant in the circus?"); } else { alert("You have entered an unknown animal which is called a " + animal); alert("This program will self-destruct in 10 seconds"); alert(" 10 - 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 ..."); } </script> Code: <script type = "text/javaScript"> var rating = prompt("Enter a movie rating (G, PG, R...)",""); rating = rating.toLowercase() switch (rating) { case "g": alert("G means this movie is rated for General Audiences"); break; case "pg": alert("PG means this movie is rated for General Audiences with Parents attending"); break; case "r": alert("R means this movie is rated for Restricted Audiences. May contain violence."); break; default: alert ("This program is rated G. We are not allowed to comment on the movie rating " + rating); } </script> I have a ondrag event handler and in that I am trying to retrieve e.ClientX but it always return 0 in Mozilla. Works fine in IE though. How can retrieve the clientX and clientY in ondrag event? I've put together a spoiler bb code, and I've noticed 2 bugs with it - I'm thinking that it's to do with the javascript end of the code. when the code is used, the page has to be refreshed for the spoiler to open and work correctly, also if there is 2 spoilers on the same page, if i click the second one, it opens the first one and not itself. I didn't type the javascript code I only did the html and css end, so I'm not sure what's going on. If any of you can help me I'd be really grateful. Here is the code: Code: <html> <head> <style type="text/css"> body,input { font-family:"Trebuchet ms",arial;font-size:0.9em; color:#333; } .spoiler { color: #494949; font-size: 10pt; font-weight:bold; text-align:left; background-color: #cbeafe ; border-top: 1px solid #9dc2d9; border-left: 1px solid #9dc2d9; border-right: 1px solid #9dc2d9; border-bottom: 2px solid #9dc2d9; padding: 2px; width:90%; min-height:18px; margin: 1px auto 1px auto; -moz-border-radius: 4px; -webkit-border-radius: 4px; -moz-box-shadow:0 0 2px #cbeafe; -webkit-box-shadow:0 0 2px #cbeafe; } .show { color: #00a2c5; font-size: 10pt; font-weight:bold; text-align:center; background-color: #fff ; border: 1px solid #fff; padding: 2px; width:25%px; min-height:5px; margin: 1px auto 1px auto; -moz-border-radius: 2px; -webkit-border-radius: 2px; -moz-box-shadow:0 0 2px #fff; -webkit-box-shadow:0 0 2px #fff; } .hide { color: #00a2c5; font-size: 10pt; font-weight:bold; text-align:center; background-color: #fff ; border: 1px solid #fff; padding: 2px; min-width:25px; min-height:5px; margin: 1px auto 1px auto; -moz-border-radius: 2px; -webkit-border-radius: 2px; -moz-box-shadow:0 0 2px #fff; -webkit-box-shadow:0 0 2px #fff; } </style> <script type="text/javascript"> function hide(id){ document.getElementById(id).style.display = 'none'; } function show(id){ document.getElementById(id).style.display = ''; } function showSpoiler(obj) { var inner = obj.parentNode.getElementsByTagName("div")[0]; if (inner.style.display == "none") inner.style.display = ""; else inner.style.display = "none"; } </script> </head> <body> <div class="spoiler"><img src="http://i.imgur.com/s5tS1.png" align="left"><img src="http://i.imgur.com/6Uq7Y.png" align="right"> <div id="show"><input type="button" class="show" onclick="hide('show'); show('hide'); showSpoiler(this);" value="Show" /> </div> <div id="hide" class="inner" style="display:none;"> <input type="button" class="hide" onclick="hide('hide'); show('show'); showSpoiler(this);" value="Hide" /> <br /><br />{param}<br /></br> </div> </div> </body> </html> Hey all, I'm trying to fully understand javascript and have a couple of questions I was hoping you could answer for me. I'm working through a book and in the book I'm creating a Bingo card that generates a random number. I'm pasting the full script below just in case it's needed. Code: function initAll () { for(var i=0; i<24; i++) { setSquare(i); } } function setSquare(thisSquare) { var currSquare= "square" + thisSquare; var colPlace= new Array (0,0,0,0,0,1,1,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4); var colBasis=colPlace[thisSquare] *15; var newNum=colBasis +getNewNum()+1; document.getElementById(currSquare).innerHTML=newNum; } function getNewNum() { return Math.floor(Math.random() *15); } //--> </script> 1. What does the [thisSquare] mean in this line of code that is bolded? I mean, I know thisSquare is whatever i is, but am I multiplying it by colPlace or what? 2. Lastly I'm confused by this part of the above code Code: var newNum=colBasis +getNewNum()+1; Why add the +1? I mean, i think getNewNum is set to pull a random number between 1 and 14. If you want to pull a number between 1 and 15, why not multiple Math.random() *16 instead of 15. Am i missing something? Sorry, I'm just not understanding why use the +1 Hey guys, as of now these lines of code... Code: function lettergrade(grade) { if (grade >= 9){ document.write("A") } else if (grade >= 8){ document.write("B") } else if (grade >= 7){ document.write("C") } else{ document.write("F | Warning, your letter grade is very low.") } }; function goletter() { document.write("Sam's letter grade on the test is: " + lettergrade(sam) + ", <br \> Sally's letter grade on the test is: " + lettergrade(sally) + ", <br \> Donald's letter grade on the test is: " + lettergrade(donald)) } ...are supposed to display the "____'s letter grade on the test is: A" or the respective letter, but instead it is displaying this... ABF | Warning, your letter grade is very low.Sam's letter grade on the test is: undefined, Sally's letter grade on the test is: undefined, Donald's letter grade on the test is: undefined Any ideas as to why this is happening? I am a novice javascript user so if there are any good alternatives that are pretty basic i'm open to ideas. Thanks guys. I have an ajax member search form that I'm just about done with but I have a couple of really irritating firefox issues. The first one is the lack of support of the click() method. I added the following but it still doesn't want to work: Code: <script> if(typeof HTMLElement != 'undefined' && !HTMLElement.prototype.click) { HTMLElement.prototype.click = function() { var evt = this.ownerDocument.createEvent('MouseEvents'); evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null); this.dispatchEvent(evt); } } </script> The second issue I'm having is with dependent dropdown selects not hiding in firefox. This seems to be due to the other functions that need to trigger onload and is dependent on what order it's loaded. Here's how I'm handling the onload functions: Code: <script> function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { if (oldonload) { oldonload(); } func(); } } } addLoadEvent(function() { ajaxFunction(document.getElementById('country').value); handleOnChange(country); setupDependencies('cbcheckedadminForm', 'adminForm', 'locationsearch'); handleOnChange2(cb_state); }); </script> I don't have an issue with either of these in chrome. IE is a WHOLE other story, it's all kinds of wonky there. I still need to go through and do some debugging for that. Any quick ideas off hand on these two issues? I'll try and post the full php file in a reply. I've used js only for simple form validations thus far. I've been working on a coldfusion/ajax dynamic select list for a few days and just about have it functioning the way I want it. My question is this. Whats the best way, if any, to handle users who turn js off. What I mean is, I have so far three separate queries for my three select lists, and are populated with ajax calls. Is there a way to get the same functionality with standard queries and page refreshes in case a visitor does have js disabled? Thanks for any tips and advice. Hi everyone; I have created a JavaScript function to show either a enabled or a disabled text input field depending on whether a checkbox has been clicked or not. It works great for that purpose. However, when I use it for more than one text input field and I submit the form, it goes back to its disabled form. This is a problem if you by mistake submit the form without filling all the fields. As I said, the submit button makes the form go disabled. Is there a way to either not have the form go disabled after submission or to have a "Oncheck" function so I can use $_SESSION to keep the checked attribute? Thanks in advance for all your help Code: <html> <head> <style type="text/css"> #Active { display:none; } </style> <script type="text/javascript"> function toggle() { if (document.getElementById) { if (document.getElementById("checkbox").checked == true) { document.getElementById("Active").style.display = "block"; document.getElementById("Inactive").style.display = "none"; } else { document.getElementById("Inactive").style.display = "block"; document.getElementById("Active").style.display = "none"; } } } </script> </head> <body> <?php echo "Add Field"; echo "<input type=\"checkbox\" name=\"check\" id=\"checkbox\" onClick=\"toggle();\" value=\"v\"/>"; echo "<form method=\"post\">"; echo "<div id=Active>"; if(isset($_SESSION['test']) && $_SESSION['test']!="") { echo "<input name=\"test\" value=\"". $_SESSION['test']."\" type=\"text\" />"; } elseif(isset($_POST['test']) && $_POST['test']!="") { echo "<input name=\"test\" value=\"". $_POST['test']."\" type=\"text\"/>"; } else { echo "<input name=\"test\" type=\"text\"/>"; } echo "<input type=\"text\" name=\"test2\" >"; echo "</div>"; echo "<div id=Inactive>"; echo "<input type=\"text\" disabled>"; echo "<input type=\"text\" disabled>"; echo "</div>"; echo "<input type=\"submit\">"; echo "</form>"; $test = $_POST['test']; $_SESSION = $_POST['test']; $test2 = $_POST['test2']; $_SESSION = $_POST['test2']; echo $test; ?> </body> </html> I've been looking at the specs for javascript, but I don't understand results I'm getting. A Date object is calculated from the number of milliseconds since Jan 1, 1970. A PHP DateTime object is calculated from the number of seconds since Jan 1, 1970, so from the latter, add three zeros, and you have milliseconds. The issue I have happens when I set the date. Below is the result of a test already filled out when I entered April 23, 2000 @ 17:00Hrs. The resulting alert shows 17:0, which is correct. But change the date to, say, 1981 and try it again. The corresponding timestamps are 356922000 and 356922000000 (Hard to see? That's '356922' ending in three zeros and six zeros respectively ;-)). My alert now reports 18:0! Since the timestamp should be good for any time after Jan 1, 1970, why is the display off for a date in this year? What mechanism is responsible for this? Yep, that's it. I'd really like to know, though... Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Simple Time Test</title> <link href="notifications.css" rel="stylesheet" type="text/css" media="screen" /> <script language="javascript" type="text/javascript"> function display_time(){ var theTime=new Date(); theTime.setTime(956534400000); alert(theTime.getHours()+':'+theTime.getMinutes()); } </script> </head> <body> <form> <input type='button' onclick='display_time();' value='click' /> </form> <?PHP /* 1. First put a date and time in the setDate() and setTime() calls. 2. Run this. The result will be a timestamp. Place that in the setTimestamp call, AND copy it into the setTime javascript call, appended with three zeros (to go from seconds to milliseconds). 3. I'm finding that when the alert pops up, the time it displays is not always the same as the output from the echo statement! */ echo '<br />'; $t3_var = new DateTime(); $t3_var->setDate(2000,04,23); $t3_var->setTime(17,0); echo 'timestamp: ' . $t3_var->getTimestamp(); echo '<br />'; $decoder1 = new DateTime(); $decoder1->setTimestamp(956534400); echo 'time: ' . $decoder1->format('m-d-Y, H:i') . '<br />'; ?> </body> </html> I don't have much experience in Javascript and would like to hear your suggestions before choosing which direction to pursue for my project. I want to design a web page which allows a user to input a file which contains a list of addresses. Then send these addresses to Google Maps API for geocoding and returned XY coordinates will be saved in a file and downloaded to the PC. Can this be done completely in Javascript(client side handling) or the input addresses need to be sent to a server and let the server talk to Google Maps API to complete geocoding and then send back the coordinates data to the browser(sever side handling). Please help!
Hi, I have a func1() called when mouseOver even fired. And while the func1() is executing if mouseOut event fires I want to exit the func1(). If anybody knows how to do this please let me know. Thanks Long time since I have been on here been really busy with college etc, I am in need of some help / advice on how to get my head around something I need to do. Basicly I want to do is be able to do two kinds of AJAX requests in one function called AJAX. Example of type one: Code: AJAX('div#example',{ type: 'post', url: 'example.php', params: {do:'test',type:2}, success: function(o) { this.innerHTML = o.responseText; } }); The above code will set the innerHTML of the div with an id equaling 'example' with everything that is visible on the page example.php when the parameters are do=test&type=2. Example of type two: Code: var div = document.getElementById('example'), example = AJAX({ type: 'post', url: 'example.php', params: {do:'test',type:2} }); if(div && example.responseText) { div.innerHTML = example.responseText; } The above code does the same thing as the code in example one but this time there is no success function but everything has been assigned to the variable 'example' which has now become an object. Basicly what I need to know is in a function like this. Code: function AJAX(t,o) {} How can I assign the current AJAX response to the success function but still be able to use 'this' to refer to the object for 'div#example', and with the second example how can I assign the AJAX response to the variable for use after the AJAX call has been done? Thank you in advance... - DJCMBear Resolved!
so, I should start by saying that I don't really understand callbacks (but I understand what they do), and here's the thing: html5 browser geolocation has an error callback which works fine EXCEPT if the user is using FF and refuses to share their location. In IE and Chrome, this produces a "permission denied" error which you can then handle. But firefox just sits there because it never receives the error. Here's an example - click on Not now in FF to see what I mean. So the only solution I can see is to make some special case for FF and this is where my question comes in - can I set a condition within the callback that says something like if it wasn't successful, but you didn't get an error, do this... I thought that if (!position&&!error) {useMaxMind("Firefox fallback"); } might do it, but it can't go in the error callback (I guess because that only fires if an error is detected) and it doesn't work in the main function (I guess because if that code runs it means the location has been found)... anyway. Here's what I have for the moment, which just sets a timeout as soon as it loads. It would be nice to have something a bit more elegant, though. thanks in advance... Code: function initialize() { // try W3C standard approach var geoTimeout = 10000; var timeOuthandler = setTimeout("useMaxMind('Timeout')", geoTimeout); if(navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latLong = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); alert("geolocation successful"); clearTimeout(timeOuthandler); showMap(latLong, 16); }, function (error) { switch (error.code) { case 0: message = "Something went wrong: " + error.message; break; case 1: message = "You denied permission to this page to retrieve a location."; break; case 2: message = "The browser was unable to determine a location: " + error.message; break; case 3: message = "The browser timed out before retrieving the location."; break; } clearTimeout(timeOuthandler); useMaxMind(message); }, {timeout:geoTimeout} ); } else { useMaxMind("No browser support"); } } Hi I am using httpXmlRequest object to call a xml web service. In order to successfully perform a task there are couple steps need to happen. 1 you have to request for a session (cookie) 2 with the cookie, we need to authenticate with the server 3 then perform other actions snippet of my code looks something like this. Basically here i am trying to get the cookie, login and then logout once logged in. function connect() { document.myForm.elements['myTextArea'].value += "connecting to teh server.\n"; try { xhttp.open("GET",urlStr + commonInfoParam, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { if(xmlDoc.readyState == 4) { var resultsTag = null; resultsTag = xmlDoc.getElementsByTagName("results"); if(resultsTag != null) { for(i=0;i<resultsTag.length;i++) { var commonTag = resultsTag[i].getElementsByTagName("common"); for(j=0;j<commonTag.length; j++) { cookie = commonTag[j].getElementsByTagName("cookie")[0].childNodes[0].nodeValue; break; } } } if(cookie != null) { document.myForm.elements['myTextArea'].value += "cookie found: " + cookie + "\n"; login(); } } }; } catch(e) { document.myForm.elements['myTextArea'].value += "Exception occurred at connect: " + e.message + "\n"; } } function login() { var loginRequestURL = "http://testconnect.com/api/xml?action=login&login=" + username+ "&password=" + password + "&session=" + cookie; try { xhttp.open("GET", loginRequestURL, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { alert('in loginResponseHandler'); if(xmlDoc.readyState == 4) { try { loginStatus = xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("code").nodeValue; if(loginStatus == 'ok') { alert("login is good: " + loginStatus); logout(); } else { } } catch(e) {} } }; } catch(e) { } } function logout() { alert("in logout"); try { xhttp.open("GET", logoutRequestURL + cookie, true); xhttp.send(); xmlDoc = xhttp.responseXML; xmlDoc.onreadystatechange = function () { alert("in logoutResponseHandler"); if(xmlDoc.readyState == 4) { try { status = xmlDoc.documentElement.childNodes[0].attributes.getNamedItem("code").nodeValue; if(status == 'ok') { alert(status); } } catch(e) {} } }; } catch(e) {} } so when I run my code in the browser, all my alert stages give me proper message as expected. But at the final alert, it hangs. I just could not figvure out what am i doing wrong. can any one pin point this out for me please? Thanks in advance. KM |