JavaScript - Draggable Div. Mouseup Event Need Js Guru :)
I set out to do a little exercise in creating draggable divs that look like app windows in pure javascript, with very little html. Problem is my mouseup event isn't always triggering and will never drop the div in the new spot.
I have a global variable to determine whether or not the div is being dragged. This is toggled on the mouseup and mousedown events on the titlebar div. I have a mouesmove event on the body so that it can determine if the global dragging variable is true or false. If true then it moves the div to the x/y coordinates of the mouse Same thing with the mouseup event. It should move the div to the x/y coordinates of the mouse Sometimes it works, sometimes it doesnt. Most of the time it acts like it just wants to select text while I'm dragging (which i thought my selectstart event would take care of) Code: <html> <head> <title>testjs</title> <script> var dragging = false; function Window(title,top,left,width,height) { this.title = (typeof title == 'undefined')?'New Window':title; this.x = (typeof top == 'undefined')?0:top; this.y = (typeof left == 'undefined')?0:left; this.width = (typeof width == 'undefined')?600:width; this.height = (typeof width == 'undefined')?400:height; this.borderStyle = 'solid'; this.windowPanel = null; this.Open = function() { var windowPanel = document.createElement('div'); windowPanel.setAttribute('id','windowPanel'); windowPanel.setAttribute('z-index', '2'); windowPanel.style.position='absolute'; windowPanel.style.left = this.x+'px'; windowPanel.style.top = this.y+'px'; windowPanel.style.width = this.width + 'px'; windowPanel.style.height = this.height + 'px'; windowPanel.style.border = 'thin solid black'; var titleBar = document.createElement('div'); titleBar.setAttribute('id','titleBar'); titleBar.setAttribute('z-index', '4'); titleBar.style.position = 'absolute'; titleBar.style.left = '0px'; titleBar.style.top = '0px'; titleBar.style.width = this.width + 'px'; titleBar.style.height = '22px'; titleBar.style.borderBottom = 'thin solid black'; titleBar.innerHTML = "<span style=position:absolute;>"+this.title+"</span>"; titleBar.addEventListener('mousedown', function(e){MouseDown(e,this)}, false); titleBar.addEventListener('mouseup', function(e){MouseUp(e,this)}, false); titleBar.addEventListener('selectstart', function(e){return false}, false); var closeButton = document.createElement('div'); closeButton.style.position = 'absolute'; closeButton.style.left = this.width - 30 + 'px'; var cbimg = document.createElement('img'); cbimg.setAttribute('src', 'close_button_red.png'); cbimg.setAttribute('width', '16'); cbimg.setAttribute('height', '16'); closeButton.appendChild(cbimg); closeButton.addEventListener('click', function(event){CloseWindow('windowPanel')}, false); document.body.addEventListener('mousemove', Mover, false); titleBar.appendChild(closeButton); windowPanel.appendChild(titleBar); document.body.appendChild(windowPanel); } } function Mover(e) { if(dragging == true) { console.log(e.pageX); document.body.style.cursor = 'move'; document.getElementById('windowPanel').style.x = e.pageX + 'px'; document.getElementById('windowPanel').style.y = e.pageY + 'px'; } else document.body.style.cursor = 'auto'; } function MouseUp(e,ele) { dragging = false; ele.parentNode.style.top = e.pageY + 'px'; ele.parentNode.style.left = e.pageX + 'px'; } function MouseDown(e,ele) { dragging = true; } function CloseWindow(wnd) { document.body.removeChild(document.getElementById(wnd)); } function init() { wnd = new Window('A new approach', 100, 150, 1024, 768); wnd.Open(); } </script> </head> <body onLoad='javascript:init()'> <a href="#" onClick="javascript:init();">Open</a> </body> </html> Similar TutorialsHi all, as the title says i am trying to keep count of the number of words a user has typed into a textbox. I have an emoticon box, something like the one that you see when you reply/start a thread here. The mouseup event fires off when the user clicks on an emoticon to display it in the textbox. The problem here is, my code below does not start counting if an emoticon is added when theres nothing in the textbox (making the emoticon the first item). I can continue to add more smileys in and they will be counted in the word limit, but the first one will not be included in the count, unless the user clicks somewhere on the screen. How can i fix this problem? Code: //#message is the textbox $(document).ready(function() { var characters = 100; $("#remainder").append(characters+"words left"); $("#emoticonsbox").mouseup(function() { var remaining = characters - $("#message").val().length; $("#remainder").html(remaining+"words left"); }); }); Okay I Don't Know Much About Javascript, But I Need A Hand I Have A Drag And Drop Script Along With A Simple Script To Make Things Appear And Disappear Bt Using This Line: ShowHide('Table'); return false; I Want to Make It So That When I Drag Something over a Div, More Preferably a Table or an Image and Then Let Go of Your Mouse (onMouseUp) It Makes the Object Disappear Or Have An Action Happen Thanx ________________________________________________________________________________________ Alright, I wrote this a while ago and This Time I'll Be More Clear And Simple. I Want To Make It So That If A Div Hovers Over A Table By Drag And Drop And You Drop Your Div in The Table An Action happens Hi i am trying to create a draggable css layer. Code: <html> <head> <style type="text/css"> #box {position:absolute; left:150;top:150; background-color:blue; height:100; width:100;} </style> <script type="text/javascript"> function start(){ var count = cnt.value var count=0; while (count=0) { var x; var y; var layer = document.getElementById('box'); x=window.event.clientX; layer.style.left=x; y=window.event.clientY; layer.style.top=y; } } function stop(){ var count = cnt.value; count = 1; } function shw(){ alert(cnt.value); } </script> <body> <input type="hidden" name="cnt" value="1"> <div id="box" onclick="start()" onrelease="stop()"> </div> <br /><br /><br /><br /><br /><br /><br /> <input type="button" name="show" value="Show" onclick="shw()"> </body> </html> It doesn't seem to work though. The loop never seems to start. btw i was also thinking couldn't i just put while(box.clicked) { or something along those lines. Thanks Hi There I am trying to create some ajax/javascript to append the scriptaculous Draggable to a number of div elements with a className of draggable. The problem is i need to get the id's of each element to make them draggable, as simply making all div elements on the page draggable would effect other elements on the page which I dont want to be so. I need to:- 1.create a collection of div elements with className - draggable 2. make a list of all the element id's 3. make all elements with said id's draggable I have left out the draggable part from the code, I have simply been trying to get the element id's to display so far Code: var dv; var dh; dv = document.getElementsByTagName('div'); if (dv.className == 'draggable') { for (var i = 0; i <= dv.length; i++) { dh = dv[i].getAttribute('id'); for (var j = 0; j <= dh.length;j++) { document.getElementById('content').innerHTML = dh[j].getAttribute('id'); } } } else { alert ("no id"); } I keep getting the alert message "no id" loaded I am designing a site where users can submit a location. I want to use Google Maps with a draggable marker which posts the lat, lon when dropped on a position. I was wondering if anyone knows of a tutorial or could point me in the direction of anything similar. I am trying to recreate this functionality on my website where you can drag a background image around and when you get ot the edges of the image it bounces back to the edge of that corrosponding side. have a look at the site in question - http://irrland.sonntagskunst.de/# so far i have recreated the top left and right edges using Code: var window_width = $(window).width(); var window_height = $(document).height(); var image_height = $("#background").height(); (2914px) var image_width = $("#background").width(); (3920px) $("#background").draggable({ scroll: false, stop: function (event, ui) { var animate_to = {}; var window_width_resized = $(window).width(); if (ui.position.left > 0) { animate_to.left = '0px'; } if (ui.position.top > 0) { animate_to.top = '0px'; } //initial size for width var image_width_gap = window_width - (image_width + ui.position.left); if (image_width_gap > 0) { animate_to.left = (0 - (image_width - window_width)) + 'px'; } //after window gets resized for width var image_width_gap_resized = window_width_resized - (image_width + ui.position.left); if (image_width_gap_resized > 0) { animate_to.left = (0 - (image_width - window_width_resized)) + 'px'; } $("#background").animate(animate_to, { duration: 1000, easing: "easeOutElastic" }); then i am using the same logic to do the bottom edge but it doesnt work any ideas here is how i thought the bottom would work Code: //initial size for height var image_height_gap = window_height - (image_height + ui.position.top); if (image_height_gap > 0) { // animate_to.top = (0 - (image_height - window_height)) + 'px'; } help would be greatly appreciated fixed.. my bg image was infact smaller Hi guys I need help on sorting out a drag&drop script I'm a bit of a rookie with programming, so I found this script somewhere and I managed to implement it in my code...unfortunately now I need to slightly modify the code, and I'm completely lost I have this drag&drop script that moves some images around the screen, but I'd like to assign an event document.getElementById("XXXXX").onclick = blablabla to each of those images. The problem is that, of course, every time I click on the image to drag it around, this activates the link. With a doubleclick event everything works smooth, however it's a solution I don't quite like. I was thinking about a way to control the code so that while the image moves the link is somehow "not active", but if the user simply clicks without dragging then it activates the .onclick function I have the following piece of code in the head section of my page, which is the actual code for dragging the elements Code: function Browser() { var ua, s, i; var ln = 1; this.isIE = false; this.isNS = false; this.version = null; ua = navigator.userAgent; s = "MSIE"; if ((i = ua.indexOf(s)) >= 0) { this.isIE = true; this.version = parseFloat(ua.substr(i + s.length)); return; } s = "Netscape6/"; if ((i = ua.indexOf(s)) >= 0) { this.isNS = true; this.version = parseFloat(ua.substr(i + s.length)); return; } // Treat any other "Gecko" browser as NS 6.1. s = "Gecko"; if ((i = ua.indexOf(s)) >= 0) { this.isNS = true; this.version = 6.1; return; } } var browser = new Browser(); // Global object to hold drag information. var dragObj = new Object(); dragObj.zIndex = 0; function dragStart(event, id) { var el; var x, y; // If an element id was given, find it. Otherwise use the element being // clicked on. if (id) dragObj.elNode = document.getElementById(id); else { if (browser.isIE) dragObj.elNode = window.event.srcElement; if (browser.isNS) dragObj.elNode = event.target; // If this is a text node, use its parent element. if (dragObj.elNode.nodeType == 3) dragObj.elNode = dragObj.elNode.parentNode; } // Get cursor position with respect to the page. if (browser.isIE) { x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } if (browser.isNS) { x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } // Save starting positions of cursor and element. dragObj.cursorStartX = x; dragObj.cursorStartY = y; dragObj.elStartLeft = parseInt(dragObj.elNode.style.left, 10); dragObj.elStartTop = parseInt(dragObj.elNode.style.top, 10); if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0; if (isNaN(dragObj.elStartTop)) dragObj.elStartTop = 0; // Update element's z-index. dragObj.elNode.style.zIndex = ++dragObj.zIndex; // Capture mousemove and mouseup events on the page. if (browser.isIE) { document.attachEvent("onmousemove", dragGo); document.attachEvent("onmouseup", dragStop); window.event.cancelBubble = true; window.event.returnValue = false; } if (browser.isNS) { document.addEventListener("mousemove", dragGo, true); document.addEventListener("mouseup", dragStop, true); event.preventDefault(); } } function dragGo(event) { var x, y; // Get cursor position with respect to the page. if (browser.isIE) { x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop; } if (browser.isNS) { x = event.clientX + window.scrollX; y = event.clientY + window.scrollY; } // Move drag element by the same amount the cursor has moved. dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px"; dragObj.elNode.style.top = (dragObj.elStartTop + y - dragObj.cursorStartY) + "px"; if (browser.isIE) { window.event.cancelBubble = true; window.event.returnValue = false; } if (browser.isNS) event.preventDefault(); } function dragStop(event) { // Stop capturing mousemove and mouseup events. if (browser.isIE) { document.detachEvent("onmousemove", dragGo); document.detachEvent("onmouseup", dragStop); } if (browser.isNS) { document.removeEventListener("mousemove", dragGo, true); document.removeEventListener("mouseup", dragStop, true); } } then in the Body, I have the DIV that can be dragged around through the "onmousedown" event Code: <div id="milano" class="aBar" style="width:auto; height:auto;" onmousedown="dragStart(event, 'milano')"> <?php print '<a href="#"><img border="0" src="images/works/thumbnails/milano.jpg" alt="" style="float:left; position:absolute; top:'.rand(50,300).'px; left:'.rand(100,500).'px"/></a>' ?> </div> then, in the Body as well, I have the javascript that I'd like to activate only if the image is clicked on BUT not dragged around Code: <script> window.onload = function () { document.getElementById("milano").onclick = function () { alert('AAAAA'); } } </script> I'm really sorry the code is REALLY messy, but as I said I'm just a rookie and I know this is not an elegant solution at all Thank you very much for your time, I really hope you can help me out with that as I spent the last 2 weeks tying to find a solution... Cheers, Mattia Hi everyone, I have some images that I want the user to be able to move around the page. So far, this script in the header allows me to do this: Code: var ie=document.all; var nn6=document.getElementById&&!document.all; var isdrag=false; var x,y; var dobj; function movemouse(e) { if (isdrag) { dobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x; dobj.style.top = nn6 ? ty + e.clientY - y : ty + event.clientY - y; return false; } } function selectmouse(e) { var fobj = nn6 ? e.target : event.srcElement; var topelement = nn6 ? "HTML" : "BODY"; while (fobj.tagName != topelement && fobj.className != "dragme") { fobj = nn6 ? fobj.parentNode : fobj.parentElement; } if (fobj.className=="dragme") { isdrag = true; dobj = fobj; tx = parseInt(dobj.style.left+0); ty = parseInt(dobj.style.top+0); x = nn6 ? e.clientX : event.clientX; y = nn6 ? e.clientY : event.clientY; document.onmousemove=movemouse; return false; } } document.onmousedown=selectmouse; document.onmouseup=new Function("isdrag=false"); The body has this: Code: <img src="images/balloons.gif" class="dragme"> Now, to be able to use this image as a link, I would have to find the displacement between the mousedown and mouseup coordinates. If the displacement is below say 10px, then the mouseup would bring them to another page. I also wanted to make it so that if the mouseup occurs in a certain area of the page, that the image would move itself to a certain spot. I've programmed a lot before, but not in JavaScript. Any help would be much appreciated. (Note: I need this done in JavaScript, not Flash, even though it might be easier). Thanks Hi Guys, I've been searching the net for both examples and pluggins to create draggable divs and although I've found many, I cant find the effect I'm after. I want the div to slow down to a stop after it has been release like when you are scrolling on one of apples mobile devices. If anybody can point me in the right direction ill be very great full. I currently am using a mootools popup on www.Hope1st.com to play his music videos.....and its working really well...only thing is on some computers (mac with firefox browser) when someone pauses the video ...the draggable box gets stuck on their mouse weird right? yea i know... so i thought of a solution...instead of the whole box being draggable why not just the black titlebar be draggable? i have absolutely no idea on how to do this....but i do have the entire JS code....are you ready? its a mouthful....a million thanks to whoever is talented enough to help me Code: var mooSimpleBox = new Class({ options: { width: 300, height: 200, opacity: '0.8', btnTitle: "Ok", closeBtn: null, boxTitle: "messageBox", boxClass: 'mainBox', id: 'myID', fadeSpeed: 500, box: null, addContentID:null, addContent: null, boxTxtColor: '#000', isVisible: false, isDrag: true }, initialize: function(options){ this.isVisible = false; if(options['isDrag']) this.isDrag = options['isDrag']; if(options['width']) this.width = options['width']; if(options['height']) this.height = options['height']; if(options['opacity']) this.opacity = options['opacity']; if(options['btnTitle']) this.btnTitle = options['btnTitle']; if(options['boxTitle']) this.boxTitle = options['boxTitle']; if(options['boxClass']) this.boxClass = options['boxClass']; if(options['boxTxtColor']) this.boxTxtColor = options['boxTxtColor']; if(options['fadeSpeed']) this.fadeSpeed = options['fadeSpeed']; if(options['id']) this.id = options['id']; if(options['closeBtn']) this.closeBtn = $(options['closeBtn']); if(options['addContentID']) this.addContentID = options['addContentID']; if(options['addContentID']) { this.addContent = $(this.addContentID).innerHTML; $(this.addContentID).setStyle('visibility','hidden'); $(this.addContentID).remove(); } this.createBox(); }, createBox: function(){ this.box = new Element('div'); this.box.addClass(this.boxClass); }, clickClose: function(){ $(this.box).effect('opacity',{ wait:true, duration:this.fadeSpeed, transition:Fx.Transitions.linear }).chain(function(){ }).start(this.opacity,0); this.box.setStyle('display','none'); this.isVisible = false; }, fadeOut: function(){ if(this.isVisible){ $(this.box).effect('opacity',{ wait:true, duration:this.fadeSpeed, transition:Fx.Transitions.linear }).chain(function(){ }).start(this.opacity,0); this.isVisible = false; } }, fadeIn: function(){ if (document.documentElement && document.documentElement.clientWidth) { theWidth=document.documentElement.clientWidth; }else if (document.body) { theWidth=document.body.clientWidth; } if (window.innerHeight) { theHeight=window.innerHeight; }else if (document.documentElement && document.documentElement.clientHeight) { theHeight=document.documentElement.clientHeight; }else if (document.body) { theHeight=document.body.clientHeight; } var top = window.getScrollTop(); var boxTop = (theHeight - this.height) / 2 ; boxTop = (boxTop + top); var boxLeft = (theWidth - this.width) / 2; this.box.setStyle('top',boxTop); this.box.setStyle('left',boxLeft); this.box.setStyle('position','absolute'); this.box.setStyle('width',this.width); this.box.setStyle('height',this.height); this.box.setStyle('opacity',this.opacity); this.box.setStyle('cursor','move'); this.box.setStyle('z-index','999990000'); this.box.setAttribute('id', this.id); this.box.setStyle('visibility','hidden'); this.box.injectInside(document.body); if(this.isVisible == false){ this.box.effect('opacity',{ wait:true, duration: this.fadeSpeed, transition: Fx.Transitions.linear }).start(0,this.opacity); this.addHT(); this.isVisible = true; } }, addHT: function(){ this.closeBtn = new Element('button', { styles: { 'border': 'none', 'background-image':'url(modules/mod_moopopup/moopopup/images/bg_button.gif)', 'color':'#fff', 'position':'absolute', 'bottom':'3px', 'right':'3px', 'width':'44px', 'height':'19px', 'font-size':'13px', 'font-weight':'bold', 'font-family':'arial', 'cursor':'pointer' } }) var width = this.width.toInt() + 5; if(window.ie){ var titleBar = new Element('div', { styles: { 'width' : width, 'height': 'auto', 'background-repeat': 'repeat-x', 'background-position': 'right top', 'line-height': '20px', 'padding': '5px 5px 5px 10px', 'position': 'absolute', 'clear': 'both', 'margin-bottom': '10px', 'top': '0px', 'left': '0px', 'color': '#eee' } }) }else{ var titleBar = new Element('div', { styles: { 'width' : width, 'height': 'auto', 'background-repeat': 'repeat-x', 'background-position': 'right top', 'line-height': 'auto', 'padding': '5px 5px 5px 10px', 'position': 'absolute', 'clear': 'both', 'margin-bottom': '10px', 'top': '0px', 'left': '0px', 'color': '#eee' } }) } $(titleBar).innerHTML = this.boxTitle; var insideDiv = new Element('div',{ styles: { 'padding':'10px' } }); insideDiv.setAttribute('id','myContent'); this.box.innerHTML = ""; insideDiv.injectInside(this.box); insideDiv.innerHTML = this.addContent; this.closeBtn.innerHTML = this.btnTitle; $(this.closeBtn).addEvent('click',this.clickClose.bindWithEvent(this)); titleBar.injectInside(this.box); this.closeBtn.injectInside(this.box); if(this.isDrag == 'true'){ this.box.makeDraggable(); } } }); mooSimpleBox.implement(new Options, new Events); Hi, Does anybody know of an example of creating a draggable iFrame in a similar way what can be done on iGoogle with the iFrame gadget using javascript? The problem that I'm having is that the elements within the iFrame can still steal the input focus when dragging the frame using the bar I'm using to initate the drag process. For example when clicking and holding the mouse down on a bar that I'm using to initiate the drag positioned above the iFrame and then moving the mouse to drag the whole frame containing the bar and iFrame I have a problem whereby if the cursor strays over the google search box on http://www.google.com the editbox steals the input focus and the dragging stops until you carefully move the mouse carefully out of the editbox control. Can anybody point me to a page/the html/css containing an iFrame containing http://www.google.com that can't be interacted with because it has a div on top of it e.g. a semitransparent one would look nice for example. Then hopefully I can incoperate the changes into my javascript on initiation of the drag of the frame to disable the elements within the iFrame? If there are any other solutions to this problem, prefereably with an example that works with browsers back as far as ie6 please let me know? Cheers Ben W Hi Guys, I am a novice at javascript. I possibly need an alternative to document.write to output specifically the value contained in Code: {exp:lg_ml:translate key="phrase[i]"} This syntax is cms specific and carries a value like horse or a translated version of it like Pferd in German. The below code outputs: {exp:lg_ml:translate key="cat"}{exp:lg_ml:translate key="dog"}{exp:lg_ml:translate key="horse"} but I want it to output in the source code of my template so it can execute correctly with predetermined values and not just on screen as the syntax instead of the actual value it holds, if you know what I mean. Anyway after hours of trying and 5 cups of cheap Nescafe coffee I need to achieve exactly the below with an alternative possibly to document.write? I also need to keep the loop. Thanks Code: <html> <body> <script type="text/javascript"> var i; var phrase = new Array(); phrase[0] = "cat"; phrase[1] = "dog"; phrase[2] = "horse"; for (i=0;i<phrase.length;i++) { document.write("{exp:lg_ml:translate key=\""+phrase[i] +"\"}"); } </script> </body> </html> Not sure if this is a CSS or Javascript fix I need. I think it will be a javascript issue/solution. Browser=Firefox 6.0.2 website page: [suspicious link removed] I am attempting to use CSS for Alert Box background. I created a class: Code: <style type="text/css"> .alert { background-color:#5f9ebe; } </style> But I have tried so many ways to use .alert and none of them work. Code: function btn1(x) { if (x.anyText.value == "") alert("Type Something") else alert("You typed: " + x.anyText.value) x.anyText.value = "" } Perhaps my question really is: How do I make class="alert" change Alert Box Background. I am very new to Javascript but learning everyday. I would prefer code help not be jquery. Thanks so much. codeFLY Hello guys I am very much a novice with javascript, but I have a problem with which I think one of the JS gurus in here might be able to help with. I have about 10,000 keywords on a single web page. There is a checkbox next to every keyword. Some of these keywords are 2 to 3 word phrases. I can type a word in a browser like Firefox and highlight all the instances that a particular keyword is found. Unfortunately there is no firefox extension that would automatically check a box next to the highlighted/found keyword. Instead of manually checking the checkbox next to every keyword highlighted in the browser here is what I would ideally like to accomplish (with the help of javascript). - Have a text field on top of the page and be able to type in a word and hit submit - if a word is found among the keywords/phrases on the page, then the checkbox next to that keyword/phrase is automatically checked. All i need is the checkboxes checked for every instance the searched keyword is found. I don't care if the above procedure is used. If someone can suggest a better route i'm open for it. I don't see why it wouldn't be possible with javascript code. Any help would be greatly appreciated. Hi, i have a complete validation code here which seems not working properly.When i filled the full name filed and i click submit, the form get submitted but when i filled the full name and filled email too and click on submit the third or fourth like country alert or helpmessage pop up. Now i am trying to fish out why it is doing that but i am not getting it now. please i know its a long code but please try to help me on where i am wrong. I will thank you for using blue thank Please i will suggest copy the code i see what i mean.Here is it Code: <html> <head> <title>Final form validation</title> <script type="text/javascript"> function formvalidator() { var Fullname=document.getElementById("Fullname"); var email=document.getElementById("email"); var addr=document.getElementById("addr"); var country=document.getElementById("country"); var zip=document.getElementById("zip"); var phone=document.getElementById("phone"); var educa=document.getElementById("educa"); var job=document.getElementById("job"); var hours=document.getElementById("hours"); if(Checkfullname(Fullname,"Please enter your full name.")){ if(Checkemail(email,"Please enter a valid email.")){ if(Checkaddr(addr,"Please enter your address for better contact.")){ if(Checkcountry(country,"Please select a country.")){ if(Checkzip(zip,"Please enter your area zip code of 5 digits.")){ if(Checkph(phone,"Please enter your phone number for better contact of 14 digits.")){ if(Checkeduca(educa,"Please select your education status.")){ if(Checkjob(job,"Please select job.")){ if(Checkhours(hours,"Please select the number of hours you want to work." )){ return true; }}}}}}}}} return false; } function Checkfullname(elem,helpmg) { var eval=elem.value; eval=eval.replace(/[^a-z\s\-\.\']/gi,""); eval=eval.replace(/^\s+|\s+$/g,""); eval=eval.replace(/\s{2,}/g," "); eval=eval.toLowerCase().replace(/\b[a-z]/g,function(w){return w.toUpperCase()}); document.getElementById("Fullname").value=eval; if(eval.length>=5 && eval.length<=50){ return true; } else{ alert(helpmg); elem.focus(); return false; }} function Checkemail(elem,help) { var eReExp=/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if(elem.value.match(eReExp)){ return true; } else{ alert(helpmg); elem.focus(); return false; }} function Checkaddr(elem,helpmg) { var eval=elem.value; eval=eval.replace(/^\s+|\s+$/g,""); eval=eval.replace(/\s{2,}/g," "); document.getElementById("addr").value=eval; if(elem.value.replace(elem.value)){ return true; } else{ alert(helpmg); elem.focus(); return false; }} function Checkcountry(elem,helpmg) { if(elem.value=="Please select country"){ alert(helpmg); elem.focus(); return false; } return true; } function Checkzip(elem,helpmg) { var zReExp=/^\d{5}$/; if(elem.value.match(zReExp)){ return true; } else{ alert(helpmg); elem.focus(); return false; }} function Checkph(elem,helpmg) { var pReExp=/^\d{14}$/; if(elem.value.match(pReExp)){ return true; } else{ alert(helpmg); elem.focus(); return false; }} function Checkeduca(elem,helpmg) { if(elem.value=="Please choose"){ alert(helpmg); elem.focus(); return false; } return true; } function Checkjob(elem,helpmg) { if(elem.value=="Please select job"){ alert(helpmg); elem.focus(); return false; } return true; } function Checkhours(elem,helpmg) { if(elem.value=="Please select hours"){ alert(helpmg); elem.focus(); return false; } return true; } </script> <style type="text/css"> #fullpage{width:100%;background-color:#f3f3f3; border:1px solid #336699;} #firstbar{ width:100%; background-color:#336699; text-align:left; font-color:white; } #field{ margin-right:70%;text-align:right;} </style> </head> <body> <h2><font color=#336699>Form validation..The power of javascript<font></h2> <p><font clor=#336699>Please note:all the field marked asteric is required and must be field.<br/>For help on filling the form just contact as at support@jobs.com.<font></p> <hr width="100%" color="#336699" size="2"> <div id="fullpage"> <form onsubmit="return formvalidator()"/> <div id="firstbar"><p><font color="white">Personal Details</font></p></div> <div id="field"> <p><font color=red>*</font>Full Name<input type="text" id="Fullname"/></p> <p><font color=red>*</font>Email<input type="text" id="email"/></p> <p><font color=red>*</font>Contact Address<input type="text" id="addr"/></p> <p><font color=red>*</font>Country<select id="country"/> <option>Please select country</option> <option>Ghana</option> <option>United States</option> <option>India</option> <option>Germany</option> <option>Italy</option> <option>Nigeria</option> <option>South Africa</option> <option>United kingdom</option> <option>Malasia</option> <option>Egypt</option> <option>France</option> <option>China</option> </select></p> <p><font color=red>*</font>Zip Code<input type="text" id="zip"/></p> <p><font color=red>*</font>Phone Number<input type="text" id="phone"/></p> <p>Fax Number<input type="text" name="fax"/></p> </div> <div id="firstbar"><p><font color="white">Educational Details & Job</font></p></div> <div id="field"> <p><font color=red>*</font>Education Status<select id="educa"/> <option>Please choose</option> <option>High School</option> <option>Diploma</option> <option>Degree</option> <option>Certified We Developer</option> <option>Certified We Designer</option> <option>others</option> </select></p> <p>Experience(Details if any)<input type="text" name="exp"/></p> <p><font color=red>*</font>Job Type<select id="job"/> <option>Please select job</option> <option>We Developer</option> <option>Web Designer</option> <option>Softwar Developer</option> <option>IT Consultancy</option> <option>Stock Trader</option> <option>Marketing Position</option> </select></p> <p><font color=red>*</font>Working Hours<select id="hours"/> <option>Please select hours</option> <option>1 to 5hurs</option> <option>1 to 8hurs</option> <option>1 to 10hurs</option> <option>1 to 12hurs</option> <option>1 to 13hurs</option> <option>1 to 15hurs</option> <option>1 to 20hurs</option> </select><p/> <p>Salary Demanded<input type="text" name="sala"/></p> <p>Comment(if any)<textarea name="text" rows="3" cols="40" wrap="virtual"/></textarea></p> <input type="submit" value="Submit Form"/> <input type="reset" value="Reset Form"/> </div></div> </form> </body> </html> Thanks.Clement Osei. Hi All, i have a really annoying problem, i have a js autosuggest file which sends/outputs suggestions to the user as they type which is working fine on its own, i have a contact form on one of my pages and it was working fine until my host upgraded to php 5.3 now everything has gone a bit haywire the contact form is interfering with the auto suggest function and when i remove the autosuggest function i get lots of errors on my contact form??? which is odd because it shouldnt have anything to do with it. here is the troublesome page and if you try and submit the form with js enabled the little loading icon next to the store search shows? which it shouldn't. the errors on the page dont effect the form from working because i have it working on another page with those errors but not with my js files for the auto suggest included. not sure if there are two ids the same somewhere which is causing the confusion between the js not sure where to start with this? do you want the files for the autosuggest or the contact form? thanks for any help really need it! Luke 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 Hi Guys, I need to amend the below so that if any version of IE is detected it calls window.resizeTo(300,400); otherwise no event or a window.moveTo(0,0); event (either one). Firefox is having problems with resizeto THANKS! <SCRIPT LANGUAGE="JavaScript"> if "any version of internet explorer" window.resizeTo(300,400); else window.moveTo(0,0); </SCRIPT> OR <SCRIPT LANGUAGE="JavaScript"> if "any version of internet explorer" window.resizeTo(300,400); else "do nothing" </SCRIPT> 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? |