JavaScript - Need Help With Event.preventdefault()
Hey guys, I had a client ask me to frankenstein two HTML5 themes together to achieve having both a countdown clock and snow effect on a "coming soon" page. You can see it he
EXSAPIEN - A New Graphic Novel The problem I'm having now is that the social media buttons are not clickable (The links work on my iPhone, but not on my laptop.) I have been able to EITHER display the snow, OR make the links work, but not both at the same time. This code seems to be the piece that is making the difference (specifically, the Code: event.preventDefault(); toward the end): Code: function init() { container = document.createElement('div'); document.body.appendChild(container); camera = new THREE.PerspectiveCamera( 75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); camera.position.z = 1000; scene = new THREE.Scene(); scene.add(camera); renderer = new THREE.CanvasRenderer(); renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT); var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture(particleImage) } ); for (var i = 0; i < 500; i++) { particle = new Particle3D( material); particle.position.x = Math.random() * 2000 - 1000; particle.position.y = Math.random() * 2000 - 1000; particle.position.z = Math.random() * 2000 - 1000; particle.scale.x = particle.scale.y = 1; scene.add( particle ); particles.push(particle); } container.appendChild( renderer.domElement ); var userAgent = navigator.userAgent || navigator.vendor || window.opera; if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) ) { document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); document.removeEventListener( 'touchstart', onDocumentTouchStart, false ); document.removeEventListener( 'touchmove', onDocumentTouchMove, false ); } else if( userAgent.match( /Android/i ) ) { document.removeEventListener( 'mousemove', onDocumentMouseMove, false ); document.removeEventListener( 'touchstart', onDocumentTouchStart, false ); document.removeEventListener( 'touchmove', onDocumentTouchMove, false ); } else { document.addEventListener( 'mousemove', onDocumentMouseMove, false ); document.addEventListener( 'touchstart', onDocumentTouchStart, false ); document.addEventListener( 'touchmove', onDocumentTouchMove, false ); } setInterval( loop, 1000 / 60 ); $('canvas').parent().addClass('snow'); } function onDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } function onDocumentTouchStart( event ) { if ( event.touches.length == 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } function onDocumentTouchMove( event ) { if ( event.touches.length == 1 ) { event.preventDefault(); mouseX = event.touches[ 0 ].pageX - windowHalfX; mouseY = event.touches[ 0 ].pageY - windowHalfY; } } I learned jscript back in 1999, so with all the new technology, multi-touch etc, that has come about in the meantime, I am effectively a n00b again. :/ Please help! What can I do here that will allow the snow effect to run while still keeping the social media links clickable?? Is there any other code I can provide that would be useful in solving the problem? Thank you!! Similar TutorialsHi 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 Hi, I was trying to code a draggable div, but ran into a weird behavior until I added "return false;" or rather "preventDefault();" to my onmousedown function. Now, I wonder why I need to prevent the default action for onmousedown triggered on a div. I understand what it usually does (e.g. preventing a form from submitting, etc.) But what default action is actually being prevented in this case? Thanks for your help. Here's the script: Code: <script type="text/javascript"> var dragging = false; var draggable; window.onload = function() { draggable = document.getElementById('draggable'); draggable.onmousedown = function(e) { dragging = true; if (e.preventDefault) e.preventDefault(); else e.returnValue = false; } } window.onmousemove = function(e) { if (!e) e = window.event; if (dragging) { draggable.style.left = e.clientX - 30 + 'px'; draggable.style.top = e.clientY - 30 + 'px'; } } window.onmouseup = function() { dragging = false; } </script> And the HTML code: Code: <div id="draggable"></div> 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 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? Hi Chaps, I have a PHP form with one input and a button. A jQuery script ('loading' animated gif) is triggered on the click of the submit button. I also have a Spry Validation field linked to the input. At the moment, if the validation is triggered, the animated gif continues and won't stop. The furthest I've managed to get with it, is to click the validation message to stop the animation, but what I'm really after is to stop the animation when the validation is visible/triggered, but I can't find a suitable Event. Code: <script type="text/javascript"> $(function() { $("#button_download") .click(function() { }) .throbber(); $("#sprytextfield1") .click(function(sprytextfield1) { $.throbberHide(); }) }); </script> If someone can point me in the right direction, that would be sweet. I have a asp:textbox where I'd like to capture when the user hits Enter, and then instead of doing whatever it normally would, then it should call a javascript function. I'm not sure how to do that, other than I suppose I should use the OnTextChanged event. But I'm not sure which parameters are sent with the event... Thanks in advance this: Code: <body onload="pack = 'Original';recoger_mapa_url();" onkeydown="pulsar_tecla(event, 'onkeypress');" onkeypress="pulsar_tecla(event, 'onkeydown');"> [/CODE] to this: Code: pack = 'Original'; recoger_mapa_url(); window.onkeydown = pulsar_tecla(window.event, 'onkeypress'); window.onkeypress= pulsar_tecla(window.event, 'onkeydown'); does not work(event is undefined). Suggestions ? I want to use an onkeydown() on my web site and the web site to know which key I pressed. Specifically know I pressed the arrow keys and store which key was pressed in a variable. any help? must work on all browsers. good day: I'm using an ajax script that receives a value into an input box and thus performs a function. I need to invoke the function immediately after the input box has a value. Currently the box has to lose focus in order for the function to work. What is the correct event handler for this to work? I have this now PHP Code: onkeyup="showResult2(this.value)" which is obviously not what I need. This is the ajax PHP Code: <script type="text/javascript"> function showResult2(strs) { if (strs.length==0) { document.getElementById("livesearch2").innerHTML=""; document.getElementById("livesearch2").style.border="0px"; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("livesearch2").innerHTML=xmlhttp.responseText; document.getElementById("livesearch2").style.border="1px solid #A5ACB2"; } } xmlhttp.open("GET","getOilChangeDate.php?q="+strs,true); xmlhttp.send(); } </script> Any thoughts on this! Mossa note: this is not homework Hi all, Currently I am doing this: Code: var e = document.getElementById('id'); e.style.color = '#ff0000'; e.style.fontFamily = 'sans-serif'; e.innerHTML = time; ...blah blah... What I'm actually doing is inserting the current time into an existing DIV and updating it every second. THAT all works. What I want to do is also set an event for that div.... something like this: e.event.onclick = 'runThisCode()'; Of course, the above doesn't work... and I'm not even sure what to ask for doing a Google search... because I get no hits (or maybe it's not possible). So, is it possible, and if so, how? Thanks! -- Roger p.s. I really don't want to edit the code itself (where that div is) because it's part of another app that may change as they update it and I don't want to have to re-patch every new release. Please can someone explain to me in simple terms which this actually does. From what I understand it will check all events until a defined event happens, such as rollover of a certain image, and then it activates a function? What I want to do is use this so that when I rollover a element such as below: Code: <img src="img url" alt="this is a tooltip" tooltip="true" /> I want it to pass the obj to a function which then runs, and then once the mouse of not over that element it will activate another function passing the previous object to this function. Although an element such as the example below would not activate these functions: Code: <img src="img url" alt="this is a tooltip"/> As the tooltip tag does not exist or has the value of false... Also, wouldn't this use a lot of resources as it checks every event which the mouse passes over? I am looking to add a calendar to my website in order to list events for each day on the calendar you click on. For example, the link below shows a calendar on the left, that when you click on a day it lists all the events that day. I have done a few searches, but am not sure if I can find a calendar that acts like this... Calendar Example Any help would be greatly appreciated! Hi I'm a newbie. Please help me. I'm using Joomla. I've got a dropdown which reads the filename from the database. When the user selects it I want an onchange event to open the pdf. I've been at it for 2 days now. Code: <?php $con = mysql_connect('localhost', 'root', ''); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("metnet", $con); $sql="SELECT * FROM newsletter"; $result = mysql_query($sql); echo "<form method='post'>"; $dropdown = "<select name='sname' onChange='location(this.form.sname)' >"; while($row = mysql_fetch_assoc($result)) { $dropdown .= "\r\n<option value='{$row['fpath']}'>{$row['fpath']}</option>"; } $dropdown .= "\r\n</select>"; echo $dropdown; ?> Hi, New to javascript. Doing web page with ASP/VB.NET. Have text boxes for UI on page. Two command buttons - Submit (for db update) and Cancel. I need the Cancel button to prompt the user to verify cancellation. Need OK/Cancel buttons on alert. If user selects Cancel-no action. If user selects OK then I want the text boxes cleared of user text input and focus returned to first text box. I think this may be the code but do not know how to apply it. function Clear() { var res=window.confirm("Please confirm cancellation-text boxes will be cleared"); if(res==true) { document.getElementById("StrtDte").value=""; document.getElementById("EndDte").value=""; document.getElementById("txtProjRegHrsAl").value=""; document.getElementById("txtProjOTHrsAl").value=""; document.getElementById("ddlRAS").focus(); } } Is this code valid or invalid for the events I need? How do I set it to fire when user clicks the ASP Cancel button? Thanks, John Dammit, for some reason this script has stopped working :/ When I click the links with the ID's of "login_dialog" and "register_dialog" a div should be shown... I'm using an event listener to do this. Code: function listener_items() { //Text field background addEvent(document.getElementById('input_username'), "click", add_username_password); addEvent(document.getElementById('input_username'), "blur", remove_username_password); addEvent(document.getElementById('input_password'), "click", add_username_password); addEvent(document.getElementById('input_password'), "blur", remove_username_password); //Switch between forms addEvent(document.getElementById('dialog_login'), "click", login_dialog_login); addEvent(document.getElementById('dialog_register'), "click", login_dialog_register); addEvent(document.getElementById('dialog_recovery'), "click", login_dialog_recovery); //Display Dialog addEvent(document.getElementById('login_dialog'), "click", navbar_login); addEvent(document.getElementById('register_dialog'), "click", navbar_register); //Close Dialog addEvent(document.getElementById('close_dialog'), "click", login_dialog_close); } //Login dialog, login form input fields background text var add_username_password = function() { add_input_text(this); }; var remove_username_password = function() { remove_input_text(this); }; //Login dialog buttons var login_dialog_login = function() { display_form('login'); }; var login_dialog_register = function() { display_form('register'); }; var login_dialog_recovery = function() { display_form('recovery'); }; //Close dialog var login_dialog_close = function() { display_dialog('login', 'hidden'); }; //Navigation bar buttons var navbar_login = function() { display_dialog('login', 'visible'); }; var navbar_register = function() { display_dialog('register', 'visible'); }; //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; addEvent ( window, "load", listener_items ); //Display/Hide login dialog function display_dialog(dialog, fun) { //Define the active menu item style var active_style = "border-right-width:3px; width:113px; border-right-color:#33CCFF; color:#FFFFFF;"; //Creat array with all forms var formsHide = Array("login","register","recovery"); var i = 0; document.getElementById('wrapper').setAttribute('style', 'visibility:' + fun); for ( i = 0; i < formsHide.length; i++ ) { if ( formsHide[i] == dialog && fun == 'visible' ); document.getElementById("dialog_" + dialog).setAttribute('style', active_style); document.getElementById(formsHide[i] + "_form").setAttribute('style', 'visibility:visible'); formsHide.splice(i, 1); } document.getElementById(formsHide[i] + "_form").setAttribute('style', 'visibility:hidden'); } } //Put text in fields if there is not data, also switch text field to password field //when focused on. Switch back to text field if no text is entered. function add_input_text(obj) { var id = obj.id.split("input_"); document.getElementById(id[1]).innerHTML = ''; } function remove_input_text(obj) { if (obj.value.length == 0) { var id = obj.id.split("input_"); var id2 = id[1].substr(0, 1).toUpperCase() + id[1].substr(1); document.getElementById(id[1]).innerHTML = id2; } } function display_form(form) { //Define the active menu item style var active_style = "border-right-width:3px; width:113px; border-right-color:#33CCFF; color:#FFFFFF;"; var forms = Array("login", "register", "recovery"); for ( c = 0; c < forms.length; c++ ) { if ( forms[c] == form ) { document.getElementById( forms[c] + "_form" ).style.visibility = "visible"; document.getElementById("dialog_" + forms[c]).setAttribute('style', active_style); document.getElementById("dialog_" + forms[c]).setAttribute('class', 'overlay_table' + ' ' + forms[c] + ' active'); forms.splice(c, 1); } } for ( c = 0; c < forms.length; c++ ) { document.getElementById("dialog_" + forms[c]).setAttribute('style', '') document.getElementById( forms[c] + "_form" ).style.visibility = "hidden"; document.getElementById("dialog_" + forms[c]).setAttribute('class', 'overlay_table' + ' ' + forms[c]); } } HTML: Code: <span><a href="#" id="login_dialog" style="color:#33CCFF;">Login</a></span> <span><a href="#" id="register_dialog" >Register</a></span> 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 there here's my problem, I want to alert each innerHTML of the tag "a" when mouse over, but it only alert when i insert "return false;" in the end of the loop, what's the problem? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <script type="text/javascript" > function show(){ var linkIt = document.getElementsByTagName("a") for(var i=0; i<linkIt.length; i++){ linkIt[i].onmouseover = function(){ alert(linkIt[i].innerHTML); } return false; } } </script> </head> <body onload="show()"> <ul id="imagegallery"> <li> <a href="images/fireworks.jpg" title="A fireworks display">Fireworks</a> </li> <li> <a href="images/coffee.jpg" title="A cup of black coffee" >Coffee</a> </li> <li> <a href="images/rose.jpg" title="A red, red rose">Rose</a> </li> <li> <a href="images/bigben.jpg" title="The famous clock">Big Ben</a> </li> </ul> </body> </html> I'm trying to assign and event to a tag during the onload function, but I don't seem to be using the correct syntax. Can someone tell me the correct way to make the assignment? Code: <!DOC HTML> <html> <head> <title> Test Event Assignment </title> <script type="text/javascript"> var eMessages = ['Main 1','Main 2','Main 3']; function eMsg(msg) { alert(msg); } window.onload = function() { var sel = document.getElementById('mmenu').getElementsByTagName('dt'); for (var i=0; i<sel.length; i++) { // sel[i].onclick="eMsg(eMessages[i])"; // does not work // sel[i].onclick="eMsg('"+eMessages[i]+"')"; // does not work sel[i].onclick=eMsg(eMessages[i]); // works, but only one time on-load } } </script> <style type="text/css"> dt { border:1px solid black; background-Color:yellow; width:50px; } </style> </head> <body> <dl id="mmenu"> <dt> A </dt> <dt> B </dt> <dt> C </dt> </dl> </body> </html> Ultimately I would like it to do something more useful than an alert, but approaching the problem one piece at a time. I can't seem to get the event listener to run an event when I focus on the text field with the ID username. JavaScript: Code: function listener_loginForm() { var fields = Array("username","password"); for ( j = 0; j < fields.length; j++ ) { var objs = document.getElementById(fields[j]); for ( var i = 0; i < objs.length; ++i ) { var elm = objs [ i ]; elm.onblur = function() { display_text_bg(this); }; if (elm.Id = "password") { elm.onfocus = function() { switch_field(this); }; } } } } //This function attaches events to elements. var addEvent = function( elm, evt, fun ) { if ( elm.addEventListener ) { elm.addEventListener( evt, fun, false ); } else if ( elm.attachEvent ) { elm.attachEvent( 'on' + evt, fun ); } else { elm [ 'on' + evt ] = fun; } }; addEvent ( window, "load", listener_loginForm ); //Put text in fields if there is not data, also switch text field to password field //when focused on. Switch back to text field if no text is entered. function display_text_bg(obj) { alert("remove text"); } function switch_field(obj) { alert("switch"); } HTML: Code: <form name="login" class="login"> <label for="username">Username: </label><br /> <input type="text" name="username" id="username" /> <br /><br /> <label for="password">Password: </label><br /> <input type="text" name="password" id="password" /> <br /><br /> <label for="remember">Remember Me? </label><br /> <br /> <span class="remember"> <span class="text">Never</span> <input type="hidden" value="never" name="rememberme" /> <ul> <li>Never</li> <li>24 Hours</li> <li>1 Week</li> <li>Always</li> </ul> </span> </form> HI, i know very little about javascript, just enough to get me into trouble actually lol. Here is what im working with. I have a custom Instant messenger for members. It uses embed object macromedia as well as javascript to diplay the window and send messages. What i want to do is simply add an onchange that when one person is typing it shows they are typing (ie xxxxx is typing....) My experience is in php and html and i looked thru the script and the javascript functions but im not sure what im looking for exactly. Do i need to have access to the swf or fla file and be able to edit them to do this? I dont see any form inputs or i would know exactly where to put the onchange lol. Im guessing the input is in the swf or fla file not sure how that works. what im guessing is that in the embed or the object tags (ill play with it) i can put something like Code: document.write('test on change\n'); i think i need to wrap that in doc write script type=javascript in quotes so it parses. If i can get that text to show up inside the IM where i want it then i can try to figure out how to set focus on box and recongize onchange and do some testing. I think i might even be able to doc write the onchange command but not sure. Thanks |