Advanced Search

Results 1 to 8 of 8

Thread: Arrow keypress function to move div works in FF, but not webkit browsers

  1. #1
    Join Date
    Feb 2006
    Posts
    223
    Thanks
    7
    Thanked 2 Times in 2 Posts

    Question Arrow keypress function to move div works in FF, but not webkit browsers

    I have this function (mostly copied from the web) that works perfectly fine in FireFox, but not Safari or Chrome. (Haven't tested in IE, and I probably won't - I just don't care anymore about IE users.) The function moves a division (#display) around the screen that contains a background image and works as a magnifier. I can drag it around with the cursor too. But can't figure why it isn't working in other browsers. Can you take a look, please? This is part 1 of an attempt to get a complex script working in webkit browsers that otherwise works fast and efficiently in FF. The function showDetailPos() just does some calculation stuff to display map position in the magnifier.

    The function is instantiated by this:
    Code:
    $(window).load(function(){
    ...
    		// define an arrow key handler
    		$('body').on('keypress', handleKeys);
    ...
    }
    Then a bunch of functions, and...
    Code:
    	function handleKeys(e) {
    		var position, 
    			draggable = $('#detail'),
    			container = $('#imagedisplay'),
    			distance = 1; // Distance in pixels the draggable should be moved
    		position = draggable.position();
    		// reposition if one of the directional keys is pressed
    		switch (e.keyCode) {
    			case 37: position.left -= distance; break; // Left
    			case 38: position.top  -= distance; break; // Up
    			case 39: position.left += distance; break; // Right
    			case 40: position.top  += distance; break; // Down
    			default: return true; // Exit and bubble
    		}
    		// keep draggable within container
    		if (position.left >= 0 && position.top >= 0 &&
    			position.left + draggable.width() <= container.width() &&
    			position.top + draggable.height() <= container.height()) {
    			draggable.css(position);
    		}
    		// update background map
    		showDetailPos();
    		// don't scroll page
    		e.preventDefault();
    	}
    Last edited by Strangeplant; 06-07-2013 at 05:12 PM. Reason: forgot to add function instantiation

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,699
    Thanks
    43
    Thanked 3,132 Times in 3,096 Posts
    Blog Entries
    12

    Default

    Code:
    $('body').on('keydown', handleKeys);
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Feb 2006
    Posts
    223
    Thanks
    7
    Thanked 2 Times in 2 Posts

    Default

    Thank you very much. It was simple, but I couldn't see it. BTW, now that the arrow keys work, why is the overall performance so very very slow in webkit, but fast in IE and lightning speed in FF? Yes, there is a lot of jQuery..... but I've never seen as bad as this. I do change src a lot, and have very large images for the background.

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,699
    Thanks
    43
    Thanked 3,132 Times in 3,096 Posts
    Blog Entries
    12

    Default

    Different browser/OS/computer combinations handle javascript animation differently.

    I'm not seeing a big difference in Chrome, IE, and the Fox, all under Win 7 on the same computer. Here's my current working code:

    Code:
    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
    #imagedisplay {
    	position: relative;
    	width: 800px;
    	height: 600px;
    	border: 1px solid black;
    }
    #detail {
    	position: absolute;
    	width: 100px;
    	height: 75px;
    	background-color: red;
    }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
    <script type="text/javascript">
    	function handleKeys(e) {
    		var position, 
    			draggable = $('#detail'),
    			container = $('#imagedisplay'),
    			distance = 1; // Distance in pixels the draggable should be moved
    		position = draggable.position();
    		// reposition if one of the directional keys is pressed
    		switch (e.keyCode) {
    			case 37: position.left -= distance; break; // Left
    			case 38: position.top  -= distance; break; // Up
    			case 39: position.left += distance; break; // Right
    			case 40: position.top  += distance; break; // Down
    			default: return true; // Exit and bubble
    		}
    		// keep draggable within container
    		if (position.left >= 0 && position.top >= 0 &&
    			position.left + draggable.width() <= container.width() &&
    			position.top + draggable.height() <= container.height()) {
    			draggable.css(position);
    		}
    		// update background map
    		//showDetailPos();
    		// don't scroll page
    		e.preventDefault();
    	}
    $(window).load(function(){
    		// define an arrow key handler
    		$('body').on('keydown', handleKeys);
    });
    </script>
    </head>
    <body>
    <div id="imagedisplay"><div id="detail"></div></div>
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Feb 2006
    Posts
    223
    Thanks
    7
    Thanked 2 Times in 2 Posts

    Default

    Well, I appreciate you taking a look at this in the various browsers, but there must be something else going on that slows the speed so very much in Safari and Chrome. I hesitate to publicly post the link to an unfinished page, but you might try it with the real data (virtually all images). It is at http://air.ccny.cuny.edu/cw/Ioc/index.php And yes, I do know that IE8 is not css3 compliant, and therefore the background map magnifier moves incorrectly; I don't have IE9 to test it with. Some code I'm working on is commented out and is still there for my reference.

    I call these jquery libraries:
    Code:
    	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
            <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js" type="text/javascript"></script>
    	<script type="text/javascript" src="../../lib/js/jquery.fileDownload.js"></script>
    	<script type="text/javascript" src="../../lib/js/jquery.simplemodal.1.4.4.min.js"></script>
    And the javascript that I'm using is this:
    Code:
    <script language="javascript">
    		// Display an external page using an iframe
    		function modalDialog(x){
    			links = ['./IocInfoOverlay.html','./IocInfoBrowser.html','./IocInfoText.html','IocInfoDataUsage.html'];
    			var src = links[x];
    			$.modal('<iframe src="' + src + '" height="600" width="750" style="border:0">', {
    				close: true,
    				containerCss:{
    					backgroundColor:"#fff", 
    					height:360, 
    					padding:20,
    					width:800
    				},
    				overlayClose:true,
    				onOpen: function (dialog) {
    					dialog.overlay.fadeIn(function () {
    						dialog.data.hide();
    						dialog.container.fadeIn(function () {
    							dialog.data.fadeIn();	 
    						});
    					});
    				},
    				onClose: function (dialog) {
    					dialog.data.fadeOut(function () {
    						dialog.container.fadeOut(function () {
    							dialog.overlay.fadeOut(function () {
    								$.modal.close();
    							});
    						});
    					});
    				}
    			});
    		}
    		var imageTypes = {
    		"Chl_IOP": "Chlorophyl Concentration IOP-NN Product&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(1/7)", 
    		  "ChlBG": "Chlorophyl Concentration OC3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(3/7)", 
    		    "Chl": "Chlorophyl Concentration NN Product&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(2/7)",
    		 "bbp443": "Particulate Backscatter at 443nm&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(4/7)", 
    		 "aph443": "Absorption due to Phytoplankton at 443nm&nbsp;(6/7)", 
    		  "ag443": "Absorption due to Gelbstoff at 443nm&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(5/7)", 
    		 "adm443": "Absorption due to Non-Algal Particulates at 443nm&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(7/7)"
    		}; 
        var x1,y1,x2,y2,distX,distY;
    	var imageMagnify, imageCrosshair = true;
    	var refLeft, refTop, startmagnifierLeft, startmagnifierTop;
    	$(window).load(function(){
    		refLeft   = Math.floor($("#field").offset().left);
    		refTop    = Math.floor($("#field").offset().top);		
    		startmagnifierLeft = refLeft +8 -130;
    		startmagnifierTop = refTop -2 +130;	
    		
    		$(window).resize(function() {											// this may not be complete?
    			refLeft   = Math.floor($("#field").offset().left);
    			refTop    = Math.floor($("#field").offset().top);
    			startmagnifierLeft = refLeft +8 -130;
    			startmagnifierTop = refTop -2 +130;
    		});
    		
    		// define draggable entity
    		$("#detail").draggable({
    			cursor: "move",
    			scroll: false,
    			drag: function(event) {
    				showDetailPos();
    			},
    			dragstart: function(event){
    				event.preventDefault();
    			}
    		});		
    		
    		// define an arrow key handler
    		$('body').on('keydown', handleKeys);
    		
    		// show magnifier in starting position and not over map, with position info
    		var originalPos = { left: startmagnifierLeft, top: startmagnifierTop };
    		$('#detail').show().offset(originalPos);
    		showDetailPos();
    			
    		$('#detail').mouseover(function(){
    			$(this).draggable("option", "stack", "#detail");
            });	
    
    		// call for initial default (recent) image title
    		changeDetail();
    		// call for initial page overlay	
    		modalDialog(0);
    	});
    
    
    	function prevdate(){
    		for (var i=2; i < document.listmenu0.fourthlevel.length; i++) {
    			if (document.listmenu0.fourthlevel[i].selected == true) {
    				document.listmenu0.fourthlevel[i].selected = false;
    				document.listmenu0.fourthlevel[i-1].selected = true;
    			}
    		}
    		goListGroup(document.listmenu0.firstlevel, document.listmenu0.secondlevel, document.listmenu0.thirdlevel, document.listmenu0.fourthlevel);
    	}
    
    	function nextdate(){
    		for (var i=document.listmenu0.fourthlevel.length-1; i > 0; i--) {
    			if (document.listmenu0.fourthlevel[i].selected == true) {
    				document.listmenu0.fourthlevel[i+1].selected = true;
    				document.listmenu0.fourthlevel[i].selected = false;
    			}
    		}
    		goListGroup(document.listmenu0.firstlevel, document.listmenu0.secondlevel, document.listmenu0.thirdlevel, document.listmenu0.fourthlevel);
    	}
    
    	function getmagnifiedimage() {
    		// toggle magnifier
    		if(imageMagnify) {
    			imageMagnify = false;
    			$('.bigimagefileMagnify').prop('value', 'Enable Magnifier');
    			$('#detail').hide('slow');
    		} else {
    			imageMagnify = true;
    			$('.bigimagefileMagnify').prop('value', 'Disable Magnifier');
    			// set original magnifier position to the left of the map
    			var originalPos = { left: startmagnifierLeft, top: startmagnifierTop };
    			$('#detail').show('slow').offset(originalPos);
    			// get new image
    			changeDetail();
    			showDetailPos();
    		}
    	}
    	
    	function getcrosshair() {
    		// toggle crosshair central block
    		if(imageCrosshair) {
    			imageCrosshair = false;
    			$('.crosshairMagnify').prop('value', 'Enable Crosshair');			
    			$('#picdetail').hide('slow');
    			// show coordinates
    			$('#count').hide('slow');
    		} else {
    			imageCrosshair = true;
    			$('.crosshairMagnify').prop('value', 'Disable Crosshair');
    			$('#picdetail').show('slow');
    			// get rid of coordinates
    			$('#count').show('slow');
    		}
    	}
    	
    	function viewBigImage() {
    		imageURL=document.getElementById("pic").src;
    		bigimageURL=imageURL.replace(/images/, "bigimages");
    		window.open(bigimageURL); 
    	}
    	
    	function changeDetail() {
    		var imageURL=document.getElementById("pic").src;
    		bigimageURL=imageURL.replace(/images/, "bigimages");
    		linkbigimageURL = 'url(' + bigimageURL + ')';
    		$('#detail').css("background-image", linkbigimageURL);
    		h = imageURL.indexOf("20");
    		if(h<0) {
    			g = "Recent   ";
    		} else { 
    			g = imageURL.substr(h+4,2) + "/" + imageURL.substr(h+6,2) + "/" + imageURL.substr(h,4) + "   ";
    		}
    		for (i in imageTypes) {
    			j = imageURL.indexOf(i);
    			if (j>1) {
    				k = imageTypes[i];
    				$('#imagetitle').html(g + k);
    				break;
    			} 
    		};
    	}
    
    	function hideDetail() {
    		$('#detail').fadeOut('slow');
    	}
    	
    	function showDetailPos() {
    		var $newPosX = Math.floor($('#detail').offset().left);
    		var $newPosY = Math.floor($('#detail').offset().top);
    		detailTop = $newPosY - refTop +4;
    		detailLeft = $newPosX - refLeft +4;
    		// calculate the map's positions with Mercator projection, lat = atan(sinh(y)), so 90 is at infinity. backgrounds (bigimages) are 8640 x 4320 px
    		detailLat = (-180*((detailTop+48)*2*12)/8640) + 90;
    		detailLon = (((detailLeft+48)*12/8640)*360) -180;
    		$('#count').html(' Lat: ' + detailLat.toFixed(2) + '<br> Lon: ' + detailLon.toFixed(2));
    		// move background
    		backgroundposition = "-" + ((detailLeft + 50)*8) + "px -" + ((detailTop + 50)*8) + "px";		
    		$('#detail').css("background-position", backgroundposition);
    	}
    
    	function getDataImage() {
    		imageURL=document.getElementById("pic").src;
    		var c = imageURL.indexOf("Recent") > -1;
    		if(c>0) {alert("This object does not have an associated data resource"); return;}
    		temp0URL=imageURL.replace(/images/, "dataimages");
    		re=new RegExp("_[\\d\\D]*?png","gi");
    		href=temp0URL.replace(re,"_all.7z");
    		$.fileDownload($(this).attr('href'), {
    		    preparingMessageHtml: "We are preparing your report, please wait...",
    			failMessageHtml: "There was a problem generating your report, please try again."
    		});
    		return false;			
    	}
    
    	function handleKeys(e) {
    		var position, 
    			draggable = $('#detail'),
    			container = $('#imagedisplay'),
    			distance = 1; // Distance in pixels the draggable should be moved
    		position = draggable.position();
    		// reposition if one of the directional keys is pressed
    		switch (e.keyCode) {
    			case 37: position.left -= distance; break; // Left
    			case 38: position.top  -= distance; break; // Up
    			case 39: position.left += distance; break; // Right
    			case 40: position.top  += distance; break; // Down
    			default: return true; // Exit and bubble
    		}
    		// keep draggable within container
    		if (position.left >= 0 && position.top >= 0 &&
    			position.left + draggable.width() <= container.width() &&
    			position.top + draggable.height() <= container.height()) {
    			draggable.css(position);
    		}
    		// update background map
    		showDetailPos();
    		// don't scroll page
    		e.preventDefault();
    	}	
    </script>

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,699
    Thanks
    43
    Thanked 3,132 Times in 3,096 Posts
    Blog Entries
    12

    Default

    I haven't figured out why exactly yet, I might not be able to. But there's some kind of extreme drain on the CPU in Chrome. Not for the keyboard and drag 'n' drop movement of the magnifier, but for whatever happens when an image is loaded. If we load no image, well one is there anyway, the 'Unavailable' one. If we keep that, it works fine in Chrome.

    Generally this type of drain is due to an endless loop of functions, but it could be something else.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Feb 2006
    Posts
    223
    Thanks
    7
    Thanked 2 Times in 2 Posts

    Default

    I finally found some browser version detection code in the javascript for the selection menu that I had adopted that seemed to bother things, and commented it out. Works much better in Safari and Chrome now that the variables are defined in these browsers.
    Code:
    /*Browser_Name = navigator.appName;
    Browser_Ver  = parseInt(navigator.appVersion);
    if((Browser_Name == "Netscape" && Browser_Ver >= 3) || (Browser_Name == "Microsoft Internet Explorer" && Browser_Ver >= 4)) Browser_Gen = ">=3rd";
    else Browser_Gen = "<3rd";
    if (Browser_Gen == '>=3rd') { 		*/  
       var imagetotl = 7;   
       var _image = 1;
    //}
    Also moved the majority of the javascript back into the head section - was at the end because various people had said that it should be there, and this appears to NOT be the case. This helped a lot. Maybe someone could comment of this.....

    Now, a question that may be out of place and should be in a new topic. I have several function calls attached to button clicks like this:
    Code:
    <input type="button" value=" Day > " onclick="nextdate();changeDetail();">
    And a typical function is like this:
    Code:
    function nextdate(){
    		for (var i=document.listmenu0.fourthlevel.length-1; i > 0; i--) {
    			if (document.listmenu0.fourthlevel[i].selected == true) {
    				document.listmenu0.fourthlevel[i+1].selected = true;
    				document.listmenu0.fourthlevel[i].selected = false;
    			}
    		}
    		goListGroup(document.listmenu0.firstlevel, document.listmenu0.secondlevel, document.listmenu0.thirdlevel, document.listmenu0.fourthlevel);
    	}
    Does changeDetail() get executed after nextdate() [including goListGroup() ] are completely finished? Meaning, it doesn't matter if changeDetail() is placed after goListGroup() inside nextdate()? I think it is always true in all browsers since javascript is linearly executed and not compiled, nor threaded. Right?

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,699
    Thanks
    43
    Thanked 3,132 Times in 3,096 Posts
    Blog Entries
    12

    Default

    Putting a script in the head of the page makes the page appear to load more slowly. There's no real difference, it's just that with scripts at the end of the page, the markup of the page loads before the scripts.The page isn't fully loaded until the scripts load though, so it just looks faster with the scripts at the end. But most scripts wait for the markup anyway, so it shouldn't matter as far as carrying out what the scripts do. Some scripts may need to do some things before the markup is rendered though, or have things best done before the markup is rendered, those scripts should remain in the head.

    Javascript is not necessarily linear. If an image's src attribute is being changed or a new image tag is being created and added to the DOM, and that image isn't cached, the script will not wait for it to be loaded unless setup to do so by having further processing continue from inside of the image's load event. If there's an AJAX call, its by definition asynchronous, meaning other things will continue on while it fetches external content. For an AJAX call to behave linearly requires that processing continue from inside its onreadystatechage (standard javascript) or success (jQuery) or complete (also jQuery) function. If setTimeouts or setIntervals are involved in javascript, the linear nature will still exist, but the actual sequence of things might be hard to logically follow/predict. Similarly for jQuery animations, which occur over time.

    From what you show I cannot tell if any of that's going on. I would have to see the changeDetail() and the goListGroup() functions. I'm assuming changeDetail() changes the image(s), if so those image(s) might need to load before the other code can work properly. And goListGroup() might fetch external content, if it does, it might not be finished when changeDetail() fires. I cannot see if any timeouts, animations, etc., are invovled.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Similar Threads

  1. Image Thumbnail Viewer II - Fading that works in all browsers
    By kittentaboo in forum Dynamic Drive scripts help
    Replies: 2
    Last Post: 05-19-2010, 09:01 PM
  2. Lightbox not working on Safari (but works on other browsers)
    By cmxsevenfoldxmc in forum Dynamic Drive scripts help
    Replies: 1
    Last Post: 10-27-2009, 03:39 AM
  3. java script code works in all browsers but internet explorer
    By suprisa in forum Dynamic Drive scripts help
    Replies: 2
    Last Post: 01-08-2009, 01:39 AM
  4. Replies: 1
    Last Post: 08-19-2008, 07:59 PM
  5. Replies: 2
    Last Post: 09-08-2007, 05:16 AM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •