Alerting .position() method not working as it should be - javascript

I've got an animation of the earth rotating around the sun. The sun stays put, but the earth keeps changing position.
I want to alert a message saying "Aligned!" or something when the earth is perfectly vertically aligned with the sun. I've been testing it out but I can't get the alert message any time other than when the page has loaded and the conditial statement corresponds to the position of the earth when the page has loaded, before the earth even gets close to aligning.
The below code will only show the position of the earth as its position is above 400. So if I say like, alert message when positionplanet.left == positionsun.left, I will get nothing.
var possun = $( "#Sun" );
var positionsun = possun.position();
var posplanet = $( "#Earth" );
var positionplanet = posplanet.position();
if (positionplanet.left >= 400)
{
alert(positionplanet.left + " and " + positionplanet.top);
}
I have a JSfiddle for the animation but for some reason I'm having trouble alerting anything at all other than just random strings. So I'll link it but it'll mainly be for reference. Demo:

I haven't checked your maths so I can't prove this definitely, but it seems like the positions never match exactly - which isn't too surprising as we're dealing with irrational numbers of pixels rounded to 10-15 decimals.
If you allow the positions to match to the nearest pixel, though, you can make it work (and no-one should be any the wiser). Also, you need to do the check for every step of the animation, instead of in the global scope like in your JSFiddle (no wonder you only get the alert when you reload the page. :) )
Putting this inside your animate() function did the trick:
var positionsun = $("#Sun").position();
var positionplanet = $("#Earth").position();
if(Math.round(positionplanet.left) == Math.round(positionsun.left))
alert("aligned!");
Also, make sure you're including jQuery if using jQuery functions (like $(...)).

Related

Jquery - Dynamically Add Text Over Time - 'Hacker Box' - 'Console'

So I'll be as clear and simple as possible. I love seeing inside a computer.
On my site, I want to have a wide box at the bottom of the page.
Inside this box, I'd like things going on inside the site to appear as text.
I understand how to make a jQuery event such as a click or a hover, spit out some text. What I don't understand is how to make that text go into a box that has say, 10 lines, and once the 11th line of text is created, the first slides up into the void, to be deleted.
After some searching around, I found this, which is getting closer to the goal.
var caption = [
"User Entered Site",
"Loading SideBar",
"Code: 01011011",
"Whatever text",
"Whatever text"
];
var i = 0;
setInterval(function() {
$("#message-box").html(caption[i]);
i++;
if (i == caption.length){i=0;}
}, 3 * 1000);
Here's the issue with the code I've found. It's actually designed for a series of changing tip at the bottom of a screen. The text will override previous text written.
Although it might be obvious I'd like to note that this sample set of text should appear in this read-only console area over time. I tried messing around with a .delay(1000) to no avail.
I don't need to get complex and write in real events for the appearing text, instead I can just create faux events - just to get the ball rolling. I figure so long as I have the main idea coded with a "false" series of "hacker-esque" codes running down this kind of... "read-only console," I'll be able to tack on some code to a new event I create in the future (click, drag, reorder, etc.) and the faux-hacker box/console will actually have some real events in it.
I may just keep faux stuff in there just to give a certain feel to this particular artistic, 'symbolically back end' website. Thank you so much guys!
Here's something that might work as a basis for what you are trying to achieve. It creates a box and then displays random messages into it, scrolling them up (by deleting the first message) when the list reaches 10 messages. I haven't attempted to style it all, you could make it look a lot prettier (and use animations to remove items slowly). I've also put a limit on how many messages it displays in total (so the snippet doesn't run forever) using the counter on i, you could remove that in your application.
var caption = [
"User Entered Site",
"Loading SideBar",
"Code: 01011011",
"Whatever text",
"Some other message"
];
var i = 0;
var h = setInterval(function() {
// already 10 messages? if so, delete the earliest
if ($("#message-box p").length == 10)
$("#message-box p").first().remove();
$("#message-box").append('<p>' + i + ': ' + caption[Math.floor(Math.random()*5)] + '</p>');
i++;
if (i == 20) clearInterval(h);}
, 1000);
#message-box {
height: 400px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="message-box"></div>

Jquery how to subtract element

Hi guys so i am trying to make a nutrition label just like this : Example
Curretnly have my db all set up. trying to get it to work one thing at the moment and then can do it with the rest.
My db looks like:
ingName: ....
fat: ...
carbs ... etc
The problem i am having right now is huge. I have been stuck on it for the last 3 days and no one seems to know whats wrong , I have a cross by ever div which is created so that the user can delete that ingredient he has added. So if they have:
Apple : 1g
Mango : 2g
Melon: 3g
Total : 6g
Lets say they dont want melon anymore then it should look like
Apple: 1g
Mango: 2g
Total: 3g
However i cant seem to get that to work. Every time i clock on the red cross it actually just makes the number in the label go blank.
My live site:
http://diet.elementalbydesign.com/bootstrap-3.3.6-dist/build.php
I cant stress enough how long i been stuck on this problem and how many people have tried to help me but yet no one has figured this out, again i am just at a wall here , really need someone to get me out :)
Again my live site to show you what is going on: My live site:
http://diet.elementalbydesign.com/bootstrap-3.3.6-dist/build.php
You can see that you can add all the elements etc, but when it comes to taking away , it goes into a shamble, if anyone does fix this problem will give them a cookie if i ever see u :)
Thanks
Edit: This is the closets i have come, but it takes -1 on every time rather than the amount set in the database
$('.selectedStuff').on("click", 'span', function(){
var fat = parseInt($("#fat").html());
fat = fat - 1;
$("#fat").html(fat);
$(this).parent().remove();
});
});
First, I think Pekka is right, you should delete the whole div instead of the span. Otherwise, the yellow box stays on.
But the problem is that when you search for an item, you do
echo "<script>$('#fat').html(".$total_fat.");</script>";
echo $row['fat'];
So then in your JavaScript when you do
<span data-fat='"+data+"' data-itemfat='"+data+"'>
You actually have
<span data-fat="<script>$(" #fat').html(2);<="" script="">2' data-itemfat='<script>$('#fat').html(2);</script>2'>X</span>
So try removing this line:
echo "<script>$('#fat').html(".$total_fat.");</script>";
When you write
var temp = 0;
$('.result').val( data );
$('#fat').html(data);
temp = data;
temp = $("#fat").val();
temp = data;
current_fat += data;
$("#fat").val(current_fat);
$('#fat').html(current_fat);
The value is not properly added. Try fixing that first, with parseInt.
The original deletion actually seemed to work!
Suggestion: Replace all the above code block with:
$('#fat').text( parseInt( $('#fat').text( ) ) + parseInt( data ) )
How about instead of removing the clicked item
$(this).remove(); /* REMOVE THE DISPLAY OF REMOVED INGREDIENT */
you remove the parent div (which includes the red cross too) like:
$(this).parent().remove();
Would that help?

checking for scrollHeight of an element sometimes returning 0

So I am checking the the scrollHeight of some dynamically generated content to determine whether or not to include a more button in the content. The user can click the more button to expand the content and see everything inside. However using the same function every time sometimes it says the scrollHeight of the elements is 0 which needless to say breaks the function for those elements. I am beyond boggled as to why this function would work 90% of the time but sometimes say the elements don't have a scrollHeight when they clearly do (they take up space on the page).
Here is the function:
function hide_show_expand_button(length){
var current_div = '';
var current_span = '';
//console.log(length);
for(var i = 0; i < length; i++){
if(document.getElementById("message_span"+i)){
current_div = document.getElementById("items_content"+i);
current_span = document.getElementById("message_span"+i);
console.log(current_div.scrollHeight, "height of the div")
if(current_span.scrollHeight > 128 && current_div.scrollHeight < 170){
console.log("inside of the check for the conversation screen");
current_div.innerHTML +="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button_conversation\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
} else if(current_span.scrollHeight > 128 && document.getElementById("items_content"+i).scrollHeight > 200 ){
current_div.innerHTML+="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button_attatchment\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
} else if(current_span.scrollHeight > 128 && current_div.scrollHeight < 200){
current_div.innerHTML +="<a href=\"#\" id='expand_colapse_button"+i+"' class=\"expand_colapse_button\" style=\"color:blue;\" onclick='expand_colapse(\""+ i + "\")'>More...</a>";
}
}
}
}
As you can see I am checking the scrollHeight on the span and on the div because I have a couple of different types of cells that are being generated and I have to place the more button in different places depending on the type of cell. This function only gets called at the end of the function that generates the content being checked and I have tried it with a setTimeout() call on the miniscule chance that it was going through this function before they were fully created (I don't know how that would happen but who knows).
P.S. This is all taking place inside of a chrome ext. I don't think that has anything to do with it but who knows. Also the position on the elements is relative as I have seen others post about scrollHeight issues with position: absolute.
Edit to make more specific:
Hopefully this helps, the cells I am trying to measure are in a containing div that gets its display set to none several different ways. What is happening above happens in one of the instances where I have navigated away (set display to none) from the container and then navigated back to it (set display to block). You can do this in about a dozen ways inside of the chrome ext. but it only says they don't have a scrollHeight (or any height for that matter I tried using getBoundingClientRect() and it returned 0 for everything) for one case which is why I am confused.
Also might be useful to know, on navigation back to the container the cells are rebuilt every time and as I stated above my function to get the scrollHeight is called at the end of the function to build the cells. So everytime you get back to the container my function is also called.
I would recommend looking at these (I couldn't locate a similar link for Chrome):
MSDN: http://msdn.microsoft.com/en-us/library/ms530302%28v=VS.85%29.aspx
MOZ: https://developer.mozilla.org/en/Determining_the_dimensions_of_elements
It seems that scrollHeight is only valid if something is large enough to need to scroll, so I would assume that 0 means no scrolling needed (all content is visible). From looking at the above links, maybe what you want is clientHeight.
I figured out the problem, It had to do with the what I was trying to check after different elements were set to display none. For some reason for 5-8 cells it was checking other content instead of the page I was on and then switching to the current content. Changing some Id's ultimately let me fix it.

Animate an element to an unknown location in the document

I have something like a message div that will contain some info of sorts.
I need to animate this text to somewhere else on the DOM, the thing is, I don't know where exactly (in offsets) the text starts from or needs to be animated to.
Take a look at this and you'll see what I mean, The order of the divs won't necessarily be in this order
Also the size of the log div will get bigger as more messages come and I need it to animate to the exact spot that the text will end up.
Not sure if that's what you're after:
$(document).ready(function() {
var dx=$('#message').offset().left;
var dy=$('#message').offset().top;
var ox=$('#log').offset().left;
var oy=$('#log').offset().top;
$("#log")
.css({"position": "absolute","left":ox+"px", "top":oy+"px"})
.animate({"top":dy+"px","left":dx+"px"}, 500, function() {
$('#message').text($(this).text());
});
});
fiddle -> http://jsfiddle.net/KhVuS/9/

Why can only my most recently added page element be resized?

I have a webpage where I can click on it to add a image. If I then click on the image it makes it bigger and if I click again it resizes it back to the original size.
If I then click somewhere else on the screen I can create another image and grow and shrink this also by clicking on it.
The problem is only the latest image can be resized by clicking even though none of the vars are being removed or changed.
This is part of a game I am working on.
I made a sample page with the least possible code to try it out and can be got here.
http://johncleary.net/hg/
What I want is to be able to click on any image at any time and it will grow and shrink
From the code on your page, I see that you are using innerHTML += ... to add new images - this isn't a very good thing, because it causes the browser to recreate all the inner elements every time you do so, and this could cause weird interactions with event handlers.
Consider using DOM methods to create and add elements, for example:
var e = document.createElement('img');
e.id = id;
e.onclick = pieceClicked; // No parameter required, this.id is available directly inside the function
...
board.appendChild(e);
Some other side notes:
You're using xPix * yPix as part of the ID: if you expect this to be unique, it may not be. For example, x = 500, y = 10 and x = 10, y = 500 will result in the same ID. How about just using xPix + ',' + yPix as a string by itself?
The several lines in which you initialize Pieces[id] can be reduced to a simpler form using object notation: Pieces[id] = { Piece: ..., xPix: ..., yPix: ... }.

Categories