i want to make a sort of compass on a mobile website.
This is what I have:
This is what i want:
I save my current location in the localstorage. Then for example 1km further I check my location and check the distance between the two points.
Now I want an arrow from the current location to the location in the localstorage.
The degrees from the phone I check with the javascript library "compass.js".
But now, how can I make the arrow to the location?
It looks as though you're trying to draw an image (an arrow) at a given rotation. Well, if we assume a modern browser (not a bad assumption for phones these days), that's quite easy. Just have an img on your page and apply a CSS transform on it.
See this site for more info on rotations in CSS: http://www.cssrotate.com/ (wow, somebody made an entire site for that…)
Now you also want to apply the rotation via JavaScript, so you'll need to change the CSS attribute dynamically. Since it's still quite new and has vendor prefixes, that's a little tricky, but not too hard. This site has a nice way to cope with it: http://www.javascriptkit.com/javatutors/setcss3properties.shtml
Putting it together, you could have this:
<img id="myarrow" src="myarrow.png" />
(blah)
<script>
// from http://www.javascriptkit.com/javatutors/setcss3properties.shtml
function getsupportedprop(proparray){
var root=document.documentElement;
for (var i=0; i<proparray.length; i++){
if (proparray[i] in root.style){
return proparray[i];
}
}
return false;
}
var cssTransform;
function setArrowRotation(x){
if(cssTransform===undefined){
cssTransform=getsupportedprop(['transform','webkitTransform','MozTransform','OTransform','msTransform']);
}
if(cssTransform){
document.getElementById('myarrow').style[cssTransform]='rotate('+x+'deg)';
}
}
</script>
Now just call setArrowRotation whenever you need to redirect the arrow.
Here's a fiddle which continuously rotates the arrow: http://jsfiddle.net/y2sxE/
Related
I have built a WordPress theme. I came across a website that created a div to follow the user's cursor. The div was enlarged smoothly when the user hovers over a button or a link.
I want to add this nice functionality as an optional feature.
I added a div to the web page, #ambition_cursor and added some basic styling. The div now shows like a blue circle. The circle has position fixed to the top left corner of the site. The position can be changed by adding a CSS translate property.
I managed to make it work with the following code:
var ambition_cursor = document.getElementById("ambition_cursor");
function ambition_mouse(e) {
var ambition_cursor_x = e.clientX; // Get the horizontal coordinate
var ambition_cursor_y = e.clientY; // Get the vertical coordinate
var ambition_cursor_pos = `translate(${ambition_cursor_x}px, ${ambition_cursor_y}px)`;
ambition_cursor.style.transform = ambition_cursor_pos;
}
window.addEventListener('mousemove', ambition_mouse);
The big downside here is the lag (?). There's quite a big delay, especially when moving the mouse around very fast. You can try it out on this site. I also put the situation in a JSFiddle; although the delay doesn't really happen there.
I didn't apply yet much styling (the default cursor is visible, so you can get a better idea of the real position). I first want this to work better, before I spent much time on that.
How can I increase the speed of this, so that the div position follows the mouse more accurately? I'm a beginner, so I don't really know which JavaScript optimisations I should make.
Current code is JavaScript, but jQuery is also an option.
Many thanks in advance!
Update: example how it looks on my computer.
All elements on the page have a transition applied. Remove/override this style and the delay goes away (tested).
As an alternative to the great answer of Joseph Atkinson:
var ambition_cursor = document.getElementById("ambition_cursor");
function ambition_mouse(e) {
ambition_cursor.style.left = e.clientX + 'px'; // Get the horizontal coordinate
ambition_cursor.style.top = e.clientY + 'px' ; // Get the vertical coordinate
}
window.addEventListener('mousemove', ambition_mouse);
See: https://levelup.gitconnected.com/use-javascript-to-make-an-element-follow-the-cursor-3872307778b4
I visited the site example, cracked open the dev console, and found throttled(20, ambition_mouse) It is not a performance issue, and the solution is to not throttle the events. It was too smooth to be a performance issue, which gave me the first clue it had to be an accidental/deliberate effect.
The issue I am having is fairly complicated to explain. I have written up a javascript that displays an image slideshow, and it works fairly well, despite using up more resources than I would like
// imgArr[] is populated before
var i = 0;
var pageLoaded = 0;
window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {
if (document.getElementById(i) != null) f();
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
}
function displaySlideshow() {
document.getElementById(destinationId).innerHTML = '<div id="slideWindow"><img src="'+imgArr[i]+'" />' + '<img src="'+imgArr[i + 1]+'" /></div>';
setTimeout('displaySlideshow()',1000*3);
i++;
if (i >= imgArr.length - 1)
i = 0;
}
loaded(destinationId,displaySlideshow);
So, this script dynamically adds two images to a HTML element, and it is wrapped in a div.
The div is styled with the height and width of the image, with the overflow (the second image) hidden.
The second image is below the first, and the slideshow is meant to go from RIGHT to LEFT.
My inquiry is twofold:
1) Is there a more efficient way of doing this?
2) How would I animate the images? Would I need to put the second image on the right of the first with CSS somehow, and then set a timer to pull the images (via a style) leftward?
I really don't recommend rolling your own animation library. The Facebook Animation Library written by the wonderful Marcel Laverdet is simple to use and comes with a lot of tutorials to get what you want out of your slideshow. (Note: ignore the FBJS stuff, it's exactly the same even if you're using it on your own site.)
If you're not using a framework, I think you'll find a lot of pain ahead of you. If you still don't want to use a framework, at least find one that is liberally licensed, and take a look at the source code. Here's one, for example.
The basic theory is, yes, you set a timer that moves the image on some sort of interval, either fixed or based on some sort of mathematical equation (eg, sin, cos, etc). By setting these intervals close together, and making lots of them, you get an "animation" in javascript. Typically, you'd use some sort of absolute positioning, moving one element off the screen as the other moves on.
I want to hide the cursor when showing a webpage that is meant to display information in a building hall. It doesn't have to be interactive at all. I tried changing the cursor property and using a transparent cursor image but it didn't solve my problem.
Does anybody know if this can be done? I suppose this can be thought of as a security threat for a user that can't know what he is clicking on, so I'm not very optimistic... Thank you!
With CSS:
selector { cursor: none; }
An example:
<div class="nocursor">
Some stuff
</div>
<style type="text/css">
.nocursor { cursor:none; }
</style>
To set this on an element in Javascript, you can use the style property:
<div id="nocursor"><!-- some stuff --></div>
<script type="text/javascript">
document.getElementById('nocursor').style.cursor = 'none';
</script>
If you want to set this on the whole body:
<script type="text/javascript">
document.body.style.cursor = 'none';
</script>
Make sure you really want to hide the cursor, though. It can really annoy people.
Pointer Lock API
While the cursor: none CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.
You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove events to that element (which you may or may not handle):
document.body.requestPointerLock();
To release the lock, you can use exitPointerLock:
document.exitPointerLock();
Additional notes
No cursor, for real
This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock or pressing ESC in some browsers).
That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.
Restrictions
As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:
document.addEventListener("click", function () {
document.body.requestPointerLock();
});
Also, requestPointerLock won't work from a sandboxed iframe unless the allow-pointer-lock permission is set.
User-notifications
Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange event on the element on which requestPointerLock was called:
document.body.addEventListener("pointerlockchange", function () {
if (document.pointerLockElement === document.body) {
// Pointer is now locked to <body>.
}
});
Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.
Listening to raw mouse movement
The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock was called on. This can be listened to simply by using the mousemove event, then accessing the movementX and movementY properties on the event object:
document.body.addEventListener("mousemove", function (e) {
console.log("Moved by " + e.movementX + ", " + e.movementY);
});
If you want to hide the cursor in the entire webpage, using body will not work unless it covers the entire visible page, which is not always the case. To make sure the cursor is hidden everywhere in the page, use:
document.documentElement.style.cursor = 'none';
To reenable it:
document.documentElement.style.cursor = 'auto';
The analogue with static CSS notation is html {cursor:none} (or, depending on what exactly you want * {cursor:none} / :root {cursor:none}).
I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do.
CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.
If you want to do it in CSS:
#ID { cursor: none !important; }
For whole html document try this
html * {cursor:none}
Or if some css overwrite your cursor: none use !important
html * {cursor:none!important}
Here is a link: http://www.avineon.com/
Open this link see on the top. Four images are rotating.
I need something similiar using Javascript.
Is it possible by using Javascript.
I don't think you'll have much luck if you try to do that in pure javascript. It might be possible using the emerging canvas and SVG libraries such as Raphael, but you'll still have cross-browser issues. That site used Flash, and I'd recommend using that if you wanted such an effect.
...why you'd want that on your website is another story though...
You could so something similar, but not exact.
Transparency = Supported in FF, Safari, IE7+
Changing image width = Place image in div with this Css
.class img {
display: block;
width: 100%;
height: 100%
}
This will make the image stretch to fill the .class div. You can then use JS to make this div narrower like the carousel does, and the image contained will animate within the div.
You would then need to track the mouse locations to determine how fast it spins.
You can use an equation using cosine for smooth acceleration from the far ends (IIRC)
You will not however be able to get the images in reverse, unless you create a copy in a server side language or use canvas.
Your best bet would not be to attempt to render something in actual 3D, but rather to use visual tricks to approximate a 3D effect. That is, use perspective / image deformation to make it look like a cube is rotating, similar to what is implemented at this page, which has a better explanation of the math involved.
Really, though, you're probably better off just using Flash.
That effect is possible in JavaScript simply by modifying each of the images width, height, and left styles over time. It's an involved script, but only needs to interpolate those three styles on the each of the image elements.
To get the rotation effect, decrement the width style of the image in a setInterval function while moving the left style property. There is a slight decrement on the height also.
You'll need two images for each side, a front and reverse. When the width decrements to zero, swap the image with it's flipped version and start incrementing the width.
Alternatively use Webkit's, and Firefox's transform css properties.
Or try one of these coverflow components that look similar:
Protoflow,
ImageFlow
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">\n');
document.write('.dyncontent{display: none; width: 728px; height: 90px;}\n');
document.write('</style>');
}
var curcontentindex=0;
var messages=new Array();
function getElementByClass(classname){
var inc=0;
var alltags=document.all? document.all : document.getElementsByTagName("*");
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
messages[inc++]=alltags[i];
}
}
function rotatecontent(){
//get current message index (to show it):
curcontentindex=(curcontentindex<messages.length-1)? curcontentindex+1 : 0;
//get previous message index (to hide it):
prevcontentindex=(curcontentindex==0)? messages.length-1 : curcontentindex-1;
messages[prevcontentindex].style.display="none"; //hide previous message
messages[curcontentindex].style.display="block"; //show current message
}
window.onload=function(){
if (document.all || document.getElementById){
getElementByClass("dyncontent");
setInterval("rotatecontent()", 5000);
}
}
</script>
<table width="100%">
<tr align="center">
<td>
<div class="dyncontent" style="display: block">
first
</div>
<div class="dyncontent">
second
</div>
<div class="dyncontent">
Third
</div>
</td>
</tr>
</table>
</body>
</html>
I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like http://www.nike.com/nikeskateboarding/v3/...)
I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's?
The trick is to use some simple JavaScript to resize the Flash DOM node:
function resizeFlash( h ) {
// "flash-node-id" is the ID of the embedded Flash movie
document.getElementById("flash-node-id").style.height = h + "px";
}
Which you call from within the Flash movie like this:
ExternalInterface.call("resizeFlash", 400);
You don't actually need to have the JavaScript code externally, you can do it all from Flash if you want to:
ExternalInterface.call(
"function( id, h ) { document.getElementById(id).style.height = h + 'px'; }",
ExternalInterface.objectID,
400
);
The anonymous function is just to be able to pass in the ID and height as parameters instead of concatenating them into the JavaScript string.
I think that the JavaScript is fairly cross-platform. If you want to see a live example look at this site: talkoftheweather.com. It may not look as though it does anything, but it automatically resizes the Flash movie size to accommodate all the news items (it does this just after loading the news, which is done so quickly that you don't notice it happening). The resize forces the browser to show a vertical scroll bar.
I've never done it that way around but I think swffit might be able to pull it off.
I halfway looked at swffit but the height (and width sometimes but mainly height) would be dynamic - swffit let's you declare a maxHeight but that number would be constantly changing...maybe I could figure out how to set it dynamically. A great place for me to start though - thanks!
What I've mostly been using if for is to limit how small you can make a "fullbrowser" flash, and for that it works great.
Happy hacking!
(and don't forget to post your findings here, I might need that too soon ;))
SWFSize
See here for more details.
Intuitsolutions.ca